Home > Article > Backend Development > How to access parent class method in php
How to access parent class methods in php: You can use [$this->method name();] to access. If there is this method in the subclass, the method in the subclass is accessed. If If there is no such method in the subclass, access the method in the parent class.
Method call:
$this->Method name(); If there is this method in the subclass, the subclass is called If there is no method in the class, the method in the parent class will be called.
parent::The method in the parent class is always called.
(Recommended tutorial: php video tutorial)
Variable calling: $this->variable name; if there is this variable in the subclass, the subclass is called in the class, if not, the
code implementation in the parent class is called:
<?php class A{ public $a1='a1'; protected $a2='a2'; function test(){ echo "hello!<hr/>"; } } 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!
Related recommendations: php training
The above is the detailed content of How to access parent class method in php. For more information, please follow other related articles on the PHP Chinese website!