在PHP的类继承用法中,有两个特殊的命名空间parent和self,parent命名空间指向父类,self命名空间指向当前类,用以下代码演示会了解的更清楚。

$this表示当前实例,在类的内部方法访问未声明为const及static的属性时,使用$this->value='phpernote';的形式。常见用法:

  •   $this->属性
  •   $this->方法

$this用来在类体内调用自身的属性和方法。

<?php
   
class Animal{             //定义基类
    public $blood;        //冷血热血属性
    public $name;

    public function __construct($blood,$name=NULL){
            $this->blood=$blood;
            if($name){
                $this->name=$name;
           }
    }
}

class A extends Animal{     // A类 由animal类派生
       public $color;
       public $legs;

       function __construct($color,$legs,$name=NULL){
                parent::__construct("warm",$name);
                $this->color=$color;
                $this->legs=$legs;
        }
}

class B extends A{    //B类 由A类派生
        function __construct($color,$name){
                parent::__construct($color,4,$name);
                self::bark();     //调用该类的另一个方法bark()
        }
        function bark(){
            print("$this->name says,'mew~ mew~'");
        }
}

$cat_xiaobai = new B("white","xiaobai");


?>

php中this,parent和self的用法

相关文章:

  • 2021-11-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-30
猜你喜欢
  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2021-11-04
相关资源
相似解决方案