上面三个关键字: this,self,parent,从字面上比较好理解,是指这,自己,父亲。实际上, this是指向当前对象的, self是指向当前类的,parent是指向父类的
(1) this
<?php
class Common_menuTree {
/**
* 主数据表字段名数组
* @var array
*/
protected $_table_fields;
/**
* 主数据表父级id字段名
* @var string
*/
protected $_fm_parent_id = "parent_id";
/**
* 构造函数
* @param array $arr 缓冲数据
*/
function __construct() {
}
/**
* 析构函数
*/
function __destruct() {
}
public function set_table($_table_fields,$_fm_parent_id) {
$this->$_table_fields = $meta_main;
$this->$_fm_parent_id = $_fm_parent_id;
return $this;
}
?>
其实this是在实例化的时候来确定指向谁,比如第一次实例化对象的时候
$test = new Common_menuTree();
this就指向了$test这个对象,所以说,this就是指向当前对象实例的指针,不指向任何其他对象或类。
(2)self
首先我们要明确一点,self是指向类本身,也就是self一般用来指向类中的静态变量或者常量
class WAP_dialback {
/**
* 命令 : 空闲
*/
const _cm_idle = "n";
/**
* 命令 : 请求呼叫
*/
const _cm_dial = "a";
private static $test;
public static $request_status = array(
self::_cm_idle => "空闲",
self::_cm_dial => "请求呼叫",
self::$test=>"测试代码"
);
}
我们这里只要注意两个地方,定义了一个静态变量$test,并且初始值化,那么调用的时候,使用的是self来调用,并且中间使用"::"来连接,就是所谓的域运算符,这时候调用的就是类自己定义的静态变 量$test,我们的静态变量与下面对象的实例无关,它只是跟类有关,就无法使用this来引用,只能使用 self来引用,因为self是指向类本身,与任何对象实例无关。换句话说,假如类里面有静态或者常量的成员,我们也必须使用self来调用。
(3)parent
parent是指向父类的,一般使用parent来调用父类的构造函数。
<?php
//基类
class Animal
{
//基类的属性
public $name; //名字
//基类的构造函数
public function __construct( $name )
{
$this->name = $name;
}
}
//派生类
class Person extends Animal //Person类继承了Animal类
{
public $personSex; //性别
public $personAge; //年龄
//继承类的构造函数
function __construct( $personSex, $personAge )
{
parent::__construct( "heiyeluren" ); //使用parent调用了父类的构造函数
$this->personSex = $personSex;
$this->personAge = $personAge;
}
function printPerson()
{
print( $this->name. " is " .$this->personSex. ",this year " .$this->personAge );
}
}
//实例化Person对象
$personObject = new Person( "male", "");
//执行打印
$personObject->printPerson(); //输出:heiyeluren is male,this year
?>
注意几个细节:成员属性都是public的,特别是父类的,是为了供继承类通过this来访问。
parent::__construct( "heiyeluren" ),这时候就使用parent来调用父类的构造函数进行对父类的初始化,因为父类的成员都是public的,于是能够在继承类中直接使用 this来调用。
总结:
this是指向对象实例的一个指针,self是对类本身的一个引用,parent是对父类的引用。