php中this,parent和self的用法

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

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

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

$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的用法_第1张图片

你可能感兴趣的:(php中this,parent和self的用法)