>  기사  >  php教程  >  php5中this关键字用法讲解

php5中this关键字用法讲解

WBOY
WBOY원래의
2016-06-06 19:56:171126검색

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 (3)parent 我们知道parent是指向父类的指针,一般我们使用parent来调用父类的构造函数。 ?php //基类 class Animal { //基类的属性 public $name; //名字 //基类的构造函数 public function __constr

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

 

  (3)parent

  我们知道parent是指向父类的指针,一般我们使用parent来调用父类的构造函数。

  

  //基类

  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", "21");

  //执行打印

  $personObject->printPerson(); //输出:heiyeluren is male,this year 21

  ?>

  我们注意这么几个细节:成员属性都是public的,特别是父类的,是为了供继承类通过this来访问。我们注意关键的地方,第25行:parent:: __construct( "heiyeluren" ),这时候我们就使用parent来调用父类的构造函数进行对父类的初始化,因为父类的成员都是public的,于是我们就能够在继承类中直接使用this来调用。

  [1] [2] 

php5中this关键字用法讲解

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.