Heim >Backend-Entwicklung >PHP-Tutorial >在子类中怎么使用父类中定义的第三方的类方法呢
在子类中如何使用父类中定义的第三方的类方法呢?
<?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 />?>
<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 />
<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 />