Home >Backend Development >PHP Tutorial >如何在子类用父类的魔术方法

如何在子类用父类的魔术方法

WBOY
WBOYOriginal
2016-06-13 12:03:21965browse

怎么在子类用父类的魔术方法

本帖最后由 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 />

子类:C
class C extends P{<br />    function __construct(){<br />        parent::__construct();<br /><br />        //想在这里给P类的$name换个值(你好)怎么做?<br />    }    <br />}


$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);
你好
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 />
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn