php在子类中调用父类的方法:
首先创建一个父类A,声明一个方法“test”
<?php class A{ public $a1='a1'; protected $a2='a2'; function test(){ echo "hello!<hr/>"; } }
然后创建子类B,用关键词“extends”继承父类A,创建子类B,使用“parent::test()”
<?php class B extends A{//若A类和B类不在同一文件中 请包含后(include)再操作 public $a1='b1'; function test2(){ $this->test(); parent::test();//子类调用父类方法 } function test() { echo $this->a1.','; echo $this->a2.','; 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如何在子类中调用父类的方法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号