Home > php教程 > php手册 > body text

php5中this关键字用法讲解

WBOY
Release: 2016-06-06 19:56:17
Original
1164 people have browsed it

欢迎进入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关键字用法讲解

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template