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

时间:2011-12-12 21:24:27

标签: php class properties visibility

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

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

这是我的问题:
当试图设置$ copy-> baz(clone()中的[2])时,它可以工作,因为我在定义这个私有属性的类中。但是,这对我来说没有意义(至少在这个例子中),因为$ 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
}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

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