PHP5经过重写后,对OOP的支持额有了很大的飞跃,成为了具备了大部分面向对象语言的特性的语言,比PHP4有了很多的面向对象的特性。这里我主要谈的是 this,self,parent 三个关键字之间的区别。从字面上来理解,分别是指 这、自己、父亲。先初步解释一下,this是指向当前对象的指针(可以看成C里面的指针),self是指向当前类的指针,parent是指向父类的指针。
1.this
<?php class UserName { //定义属性 private $name; //定义构造函数 function __construct( $name ) { $this->name = $name; //这里已经使用了this指针语句① } //析构函数 function __destruct(){} //打印用户名成员函数 function printname() { print( $this->name ); //再次使用了this指针语句②,也可以使用echo输出 } } $obj1 = new UserName( "Jim" ); //实例化对象 语句③ //执行打印 $obj1->printname(); //输出: PBPHome echo "<br>"; //输出:回车 //第二次实例化对象 $obj2 = new UserName( "Jack" ); //执行打印 $obj2->printname(); //输出:PHP ?>
Jim
Jack
2.self
<?php class Counter//定义一个Counter的类 { //定义属性,包括一个静态变量$firstCount,并赋初值0 语句① private static $firstCount = 0; private $lastCount; //构造函数 function __construct() { $this->lastCount =++self::$firstCount;//使用self来调用静态变量 语句② } //打印lastCount数值 function printLastCount() { print( $this->lastCount ); } } //实例化对象 for($i=0;$i<10;$i++){ $obj = new Counter(); $obj->printLastCount(); echo '<br>'; } ?>
1
2
3
4
5
6
7
8
9
10
3.parent
<?php //建立基类Animal class Animal { public $name; //基类的属性,名字$name //基类的构造函数,初始化赋值 public function __construct( $name ) { $this->name = $name; } } //定义派生类Person 继承自Animal类 class Person extends Animal { public $personSex; //对于派生类,新定义了属性$personSex性别、$personAge年龄 public $personAge; //派生类的构造函数 function __construct( $personSex, $personAge ) { parent::__construct( "Jim"); //使用parent调用了父类的构造函数 语句① $this->personSex = $personSex; $this->personAge = $personAge; } //派生类的成员函数,用于打印,格式:名字 is name,age is 年龄 function printPerson() { print( $this->name. " is ".$this->personSex. ",age is ".$this->personAge ); } } //实例化Person对象 $personObject = new Person( "male", "21"); //执行打印 $personObject->printPerson();//输出结果:Jim is male,age is 21 ?>