【问题标题】:PHP Private property visible outside of object (within same class)PHP 私有属性在对象外部可见(在同一类中)
【发布时间】:2012-01-18 20:17:40
【问题描述】:

在这个例子中,我有一个抽象类和两个常规类。抽象类不应该单独使用,所以它的构造函数是受保护的。一些函数是在抽象类中定义的。

其中一个函数是“克隆”函数,它应该返回当前对象的一个​​新实例。 此函数复制当前对象。

这是我的问题:
当试图设置 $copy->baz ([2] in clone()) 时,它可以工作,因为我在定义这个私有属性的类中。然而,这对我来说没有意义(至少在这个例子中),因为 $copy 是另一个对象(同一个类) - 是否可以强制 PHP 使用魔法设置器(“设置私有属性”)时设置另一个对象(不是类)的私有属性?

abstract class ac
{
    private $baz = "fakedefault";

    function __set($name, $value)
    {
        die("Setting private property!");
    }

    function clone()
    {
        $copy = clone $this; //make copy
        //Test:
        $this->baz = "newval"; //[1] Works as expected
        $copy->baz = "newval"; //[2] Does not die!
        return $copy; //return copy
    }
}

class c1 extends ac
{
    function foo()
    {
        print $this->baz;
    }
}

class c2 extends ac
{
    function foo()
    {
        print $this->baz;
    }
}

function dostuff()
{
    $o = new c1();
    $o->baz = "thiswontwork"; //Private -> doesn't work
}

【问题讨论】:

  • 请查看我对答案的最新编辑 - 我认为这可能会有所帮助。谢谢

标签: php class properties visibility


【解决方案1】:

您需要将方法命名为 __clone,而不是 clone

[编辑替换代码]

试试这个:

<?

header( 'content-type: text/plain' );
abstract class ac
{
    private $name = 'default-value';

    public function __set($name, $value)
    {
        throw new Exception( 'Undefined or private property.' . $name );
    }

    function __clone()
    {
        // this does work - $this->name is private but is accessible in this class
        $this->name = 'Isaac Newton';
    }
}

class c1 extends ac
{

    function __clone()
    {
        // this does not work - $this->name is private to ac and can't be modified here
        $this->name = 'Isaac Newton';
    }

    function echoName()
    {
        echo $this->name;
    }
}

function dostuff()
{
    $o = new c1();
    //$o->otherVariable = 'test'; // won't work - it's undefined
    $a = clone $o;
}

dostuff();

【讨论】:

    【解决方案2】:
    $this->__set("baz", "newval");
    

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 2018-08-26
      • 2011-02-13
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      相关资源
      最近更新 更多