Home > Backend Development > PHP Tutorial > 在子类中怎么使用父类中定义的第三方的类方法呢

在子类中怎么使用父类中定义的第三方的类方法呢

WBOY
Release: 2016-06-13 12:21:54
Original
1082 people have browsed it

在子类中如何使用父类中定义的第三方的类方法呢?

<?php<br />class a {<br />	var $c;<br />	function aa() {<br />		echo "I'm a!";<br />	}<br />	function gc(){<br />		$this->c = new c;<br />	}<br />}<br />class b extends a {<br />	function bb() {<br />		echo "I'm b!";<br />	}<br />	function dc(){<br />		$this->c->c();//报错: Call to a member function c() on a non-object<br />		//在子类中如何使用父类中定义的第三方的类方法呢?<br />	}<br />}<br />class c {<br />	function c() {<br />		echo "I'm c!";<br />	}<br />}<br />$a = new a;<br />$b = new b;<br />$a->aa();//I'm a!<br />$a->gc();//I'm c!<br />$b->dc();//报错: Call to a member function c() on a non-object<br />?>
Copy after login

------解决思路----------------------
<br />class a {<br />    var $c;<br />    function aa() {<br />        echo "I'm a!";<br />    }<br />    function gc(){<br />        $this->c = new c;<br />    }<br />}<br />class b extends a {<br />    function bb() {<br />        echo "I'm b!";<br />    }<br />    function dc(){<br />		parent::gc();//要先实例化c $this->c才有值<br />		//由于 方法c() 和类c 同名,实例化时会自动调用(构造方法) 输出第三个I'm c!<br />        $this->c->c();//调用方法c() ,输出I'm c!<br />        <br />    }<br />}<br />class c {<br />    function c() {<br />        echo "I'm c!";<br />    }<br />}<br />$a = new a;<br />$b = new b;<br />$a->aa();//I'm a!<br />$a->gc();//I'm c!<br />$b->dc();//报错: Call to a member function c() on a non-object<br />//I'm a!I'm c!I'm c!I'm c!<br />
Copy after login

------解决思路----------------------
<br /><?php<br />class a {<br />    public $c;<br />    function aa() {<br />        echo "I'm a!";<br />    }<br />    function gc(){<br />        $this->c = new c;<br />    }<br />}<br />class b extends a {<br />    function bb() {<br />        echo "I'm b!";<br />    }<br />    function dc(){<br />        $this->gc(); // 执行gc方法创建c对象<br />        $this->c->c();<br />    }<br />}<br />class c {<br />    function c() {<br />        echo "I'm c!";<br />    }<br />}<br />$a = new a;<br />$b = new b;<br />$a->aa();//I'm a!<br />$a->gc();//I'm c!<br />$b->dc();//I'm c!<br />?><br />
Copy after login


$a = new a;
$b = new b;

$a 与 $b是两个类对象,
对于$b来讲,并没有执行继承类 a的gc方法,所以$this->c为null
修改方法如下,在$b中执行一下gc即可。

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