php 子类中如何调用父类的变量和方法

[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{//若A类和B类不在同一文件中 请包含后(include)再操作  
  11.     public $a1='b1';  
  12.     function test2(){  
  13.             $this->test();  
  14.               parent::test();//子类调用父类方法  
  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. ?>


方法的调用:$this->方法名();如果子类中有该方法则调用的是子类中的方法,若没有则是调用父类中的

          parent::则始终调用的是父类中的方法。

变量的调用:$this->变量名;如果子类中有该变量则调用的是子类中的,若没有则调用的是父类中的

猜你喜欢

转载自blog.csdn.net/pingyankedike53566/article/details/71430169
今日推荐