PHP5中的this,self和parent关键字详解(3) 13 }14 }1516 //派生类17 class Person extends Animal //Person类继承了Animal类18 {19 public $personSex; //性别20 public $personAge; //年龄2122 //继承类的构造函数23 function __construct( $personSex, $personAge )24 {25 parent::__construct( "heiyeluren" ); //使用parent调用了父类的构造函数26 $this->personSex = $personSex; 27 $this->personAge = $personAge;28 }2930 function printPerson()31 {32 print( $this->name. " is " .$this->personSex. ",this year " .$this->personAge );33 }34 }3536 //实例化Person对象37 $personObject = new Person( "male", "21");3839 //执行打印40 $personObject->printPerson(); //输出:heiyeluren is male,this year 214142 ?>
我们注意这么几个细节:成员属性都是public的,特别是父类的,是为了供继承类通过this来访问。我们注意关键的地方,第25行:parent::__construct( "heiyeluren" ),这时候我们就使用parent来调用父类的构造函数进行对父类的初始化,因为父类的成员都是public的,于是我们就能够在继承类中直接使用this来调用。