私有属性在对象外部可见(在同一个类中)


PHP Private property visible outside of object (within same class)

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

其中一个函数是"克隆"函数,它应该返回当前对象的新实例。这个函数复制当前对象。 我的问题是:
当尝试在clone()中设置$copy->baz([2])时,它可以工作,因为我在定义此私有属性的类中。然而,这对我来说没有意义(至少在这个例子中),因为$copy是另一个对象(属于同一个类)——在设置另一个对象(不是类)的私有属性时,是否有可能强制PHP使用魔法setter("设置私有属性")?
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
}

您需要将您的方法命名为__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();

$this->__set("baz", "newval");