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

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

WBOY
Release: 2016-06-13 12:03:21
Original
966 people have browsed it

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

本帖最后由 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
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template