怎么在子类用父类的魔术方法
本帖最后由 meenw 于 2014-07-29 12:47:44 编辑 父类:P
<br />class P{<br /> private $name="";<br /> function __construct(){<br /> $this->name="hello";<br /> }<br /> public function __set($name, $value){ <br /> $this->$name=$value; <br /> }<br /> public function showName(){<br /> echo $this->name;<br /> }<br />}<br />
Copy after login
子类:C
class C extends P{<br /> function __construct(){<br /> parent::__construct();<br /><br /> //想在这里给P类的$name换个值(你好)怎么做?<br /> } <br />}
Copy after login
$c=new C;
$c->showName;
然后输出:你好
怎么实现?
------解决方案--------------------class P{<br /> private $name="";<br /> function __construct(){<br /> $this->name="hello";<br /> }<br /> public function __set($name, $value){ <br /> $this->$name=$value; <br /> }<br /> public function showName(){<br /> echo $this->name;<br /> }<br />}<br />class C extends P{<br /> function __construct(){<br /> parent::__construct();<br /> $this->name = '你好';<br /> } <br />}<br />$c=new C;<br />$c->showName();<br /><br />print_r($c);
Copy after login
你好
C Object
(
[name:P:private] => 你好
)
------解决方案--------------------<br />class P{<br /> private $name="";<br /> function __construct(){<br /> $this->name="hello";<br /> }<br /> public function __set($name, $value){<br /> $this->$name=$value;<br /> }<br /> public function showName(){<br /> echo $this->name;<br /> }<br />}<br /><br /><br />class C extends P{<br /> function __construct(){<br /> parent::__construct();<br /> //想在这里给P类的$name换个值(你好)怎么做?<br /> $this->name = '你好';<br /> }<br />}<br /><br />$obj = new C();<br />$obj->showName();<br />
Copy after login