How to call variables and methods of parent class in php subclass

[php]  view plain  copy
  1. <?php  
  2.   
  3. class A{  
  4.     public$a1='a1';   
  5.     protected$a2='a2';   
  6.     function test(){  
  7.            echo"hello!<hr/>";   
  8.     }  
  9. }  
  10. class  B  extends  A{ //If class A and class B are not in the same file, please include and then operate  
  11.     public$a1='b1';   
  12.     function test2(){  
  13.             $this->test();  
  14.               parent::test(); //Subclass calls parent class method  
  15.     }  
  16.     function test()  
  17.     {     
  18.         echo$this->a1.',';   
  19.         echo$this->a2.',';   
  20.         echo"b2_test_hello<hr/>";   
  21.     }  
  22. }  
  23. $a = new B();  
  24. $a->test();//b1,a2,b2_test_hello  
  25. $a->test2();//b1,a2,b2_test_hello//hello!  
  26.   
  27. ?>


Method call: $this->method name(); If there is this method in the subclass, the method in the subclass is called, if not, the

          parent:: in the parent class is called, and the method in the parent class is always called Methods.

Variable call: $this->variable name; if there is this variable in the subclass, it will be called in the subclass, if not, it will be called in the parent class

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325905029&siteId=291194637