首页  >  文章  >  后端开发  >  php如何在子类中调用父类的方法

php如何在子类中调用父类的方法

WJ
WJ原创
2020-06-01 13:46:403445浏览

php如何在子类中调用父类的方法

php在子类中调用父类的方法:

首先创建一个父类A,声明一个方法“test”

<?php
class A{
    public $a1=&#39;a1&#39;;
    protected $a2=&#39;a2&#39;;
    function test(){
           echo "hello!<hr/>";
    }
}

然后创建子类B,用关键词“extends”继承父类A,创建子类B,使用“parent::test()”

<?php
class B extends A{//若A类和B类不在同一文件中 请包含后(include)再操作
    public $a1=&#39;b1&#39;;
    function test2(){
            $this->test();
              parent::test();//子类调用父类方法
    }
    function test()
    {   
        echo $this->a1.&#39;,&#39;;
        echo $this->a2.&#39;,&#39;;
        echo "b2_test_hello<hr/>";
    }
}
$a = new B();
$a->test();//b1,a2,b2_test_hello
$a->test2();//b1,a2,b2_test_hello//hello!

相关参考:php中文网

以上是php如何在子类中调用父类的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn