php中this、self、parent解析
概述:
this:指向类当前对象的指针;self:指向类本身,一般指向类中的静态变量;parent:指向父类的指针,一般使用parent来调用父类的构造函数。
下面通过程序详细介绍:
1、this
<?php class Model_this{ private $name; //定义类私有成员 function __construct($name){ //PHP 5 允许定义构造函数和析构函数 $this->name = $name; } function __destruct(){} function showName(){ echo $this->name."\n"; } } $obj_1 = new Model_this("Jim"); $obj_2 = new Model_this("Tom"); $obj_1->showName(); //输出Jim $obj_2->showName(); //输出Tom ?>
this是在对象实例化的时候确定指向,指向类当前的对象。
2、self
<?php class Model_self{ private static $num = 0; private $sum; function __construct(){ $this->sum = ++self::$num; } function showSum(){ echo $this->sum."\n"; } } $obj_3 = new Model_self(); $obj_3->showSum(); //输出1 $obj_4 = new Model_self(); $obj_4->showSum(); //输出2 ?>
self和类的对象没有关系,它指向类本身。
3、parent
<?php class BaseClass{ public $name; function __construct($name){ $this->name = $name; } } class SubClass extends BaseClass{ private $sex, $age; function __construct($sex, $age){ parent::__construct("Jim"); $this->sex = $sex; $this->age = $age; } function showInfo(){ echo $this->name." is a ".$this->sex; echo " and ".$this->age." years old.\n"; } } $obj_jim = new SubClass("man", 23); $obj_jim->showInfo(); //输出 Jim is a man and 23 years old. ?>
使用parent来调用父类的构造函数。