欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2024-01-26 20:03:10
...
父类:P
class P{    private $name="";    function __construct(){        $this->name="hello";    }    public function __set($name, $value){                $this->$name=$value;          }    public function showName(){        echo $this->name;    }}

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


$c=new C;
$c->showName;
然后输出:你好
怎么实现?


回复讨论(解决方案)

class P{    private $name="";    function __construct(){        $this->name="hello";    }    public function __set($name, $value){                $this->$name=$value;          }    public function showName(){        echo $this->name;    }}class C extends P{    function __construct(){        parent::__construct();        $this->name = '你好';    }    }$c=new C;$c->showName();print_r($c);
你好
C Object
(
[name:P:private] => 你好
)

class P{    private $name="";    function __construct(){        $this->name="hello";    }    public function __set($name, $value){        $this->$name=$value;    }    public function showName(){        echo $this->name;    }}class C extends P{    function __construct(){        parent::__construct();         //想在这里给P类的$name换个值(你好)怎么做?		 $this->name = '你好';    }}$obj = new C();$obj->showName();