2011-12-12 34 views
1

在這個例子中,我有一個抽象類和兩個常規類。抽象類不應該單獨使用,所以它的構造函數是受保護的。一些函數在抽象類中定義。PHP在對象之外可見的私有屬性(在同一個類中)

其中一個函數是一個「克隆」函數,它應該返回當前對象的新實例。 該函數複製當前對象。

這是我的問題:
當試圖在clone()中設置$ copy-> baz([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 
} 
+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(); 
相關問題