php构造函数实例讲解

  PHP官网定义:

  

复制代码 代码如下:

  构造函数是类中的一个特殊函数,当使用 new 操作符创建一个类的实例时,构造函数将会自动调用。当函数与类同名时,这个函数将成为构造函数。如果一个类没有构造函数,则调用基类的构造函数,如果有的话,则调用自己的构造函数

  如a.php一个class a类:

  

复制代码 代码如下:

  <?php

  class a{

  function __construct(){

  echo 'class a';

  }

  }

  b.php有个class b类继承a类:

  

复制代码 代码如下:

  <?php

  include 'a.php';

  class b extends a{

  function __construct(){

  echo '666666';

  //parent::__construct();

  }

  function index(){

  echo 'index';

  }

  }

  $test=new b();

  这样写的话,b类有自己的构造函数,那么实例化b类的时候,自动运行构造函数,此时默认不运行父类的构造函数,如果同时要运行父类构造函数,要声明parent::__construct();

  

复制代码 代码如下:

  <?php

  include 'a.php';

  class b extends a{

  function index(){

  echo 'index';

  }

  }

  $test=new b();

  此时b类没有自己的构造函数,那么将默认执行父类的构造函数。