日志

PHP中this、self和parent的区别

this

this是指向类实例化对象的指针,因此它指向的不是类而是类实例化后的对象,例如 $obj = new Animal(); 此时类内部定义的$this指的就是$obj这个对象,而不是Animal这个类.

self

self是类自身的引用,通常指向类的静态成员常量,在类体内引用静态成员和常量时不能用$this->var / $this->foo() 的形式.

parent

parent是指向父类的引用,通过parent可以访问父类方法(不管是否为静态)、父类静态成员父类常量,但不可以访问父类的非静态属性.(注意:$this也可以调用父类方法,但是如果继承类覆盖了父类方法A,那么$this->A()指的是继承类的A()方法,而parent::A()指的依然是父类的A()方法,不受覆盖影响

例子

<?php
class Object{
    public $name = '';
	
    public function __construct($name){
	$this->name = $name;
    }

    protected function foo(){
	echo 'Object foo function'.PHP_EOL;
    }
}

class Animal extends Object{
    public static $count = 0;
    const OBJECT_ID = 999;

    public function __construct($name){
	parent::__construct($name);
	self::count();
	parent::foo();
	$this->foo();
    }

    protected function foo(){
	echo 'Animal foo function'.PHP_EOL;
    }

    private static function count(){
	self::$count += 1;
    }
}

$a = new Animal('dog');
echo $a->name;
echo PHP_EOL;
echo Animal::$count;
echo PHP_EOL;
echo Animal::OBJECT_ID;
echo PHP_EOL;

$c = new Animal('cat');
echo $c->name;
echo PHP_EOL;
echo Animal::$count;
echo PHP_EOL;
echo Animal::OBJECT_ID;

/*****Output*****
 
Object foo function
Animal foo function
dog
1
999
Object foo function
Animal foo function
cat
2
999

*******************/
转载请注明出处:

© http://hejunhao.me