在PHP中,$this指的是实例化的对象,而不是类本身,如下代码:
class A{
public $name;
function __construct($x){
$this->name = $x;
}
public function show(){
echo $this->name;
}
}
$a = new A(‘zym’);
$a->show();//zym
在PHP中,self指的是类本身,而不是实例化的对象,如下代码:
class A{
public $name;
private $sex;
protected $height;
static $age = ’23’;
function __construct($x,$y,$z){
$this->name = $x;
$this->sex = $y;
$this->height = $z;
//self::$age = $m;
}
private function go(){
echo ‘go’;
}
public function show(){
echo $this->name.'<br/>’;
echo $this->sex.'<br/>’;
echo $this->height.'<br/>’;
echo self::$age.'<br/>’;
}
static function showAge(){
echo ‘my age is 23’;
}
}
$a = new A(‘zym’,’man’,’180cm’);
echo A::$age;//23
$echo $a->age;//报错
在PHP中,子类继承父类并改写了父类中的方法,但是依然想要调用父类中的方法,就用parent,如下代码:
class A{
public function show(){
echo 123;
}
}
class B extends A{
public function show(){
echo ‘456’.'<br/>’;
parent::show();
}
}
$b = new B();
$b->show();//456 123