php构造函数实例讲解_php技巧

WBOY
Release: 2016-05-17 08:52:53
Original
896 people have browsed it

PHP官网定义:

复制代码 代码如下:

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

如a.php一个class a类:
复制代码 代码如下:

class a{
 function __construct(){
  echo 'class a';
 }
}

b.php有个class b类继承a类:
复制代码 代码如下:

include 'a.php';
class b extends a{
 function __construct(){
  echo '666666';
  //parent::__construct();
 }

 function index(){
  echo 'index';
 }
}
 

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

include 'a.php';
class b extends a{
 function index(){
  echo 'index';
 }
}
 

$test=new b();
此时b类没有自己的构造函数,那么将默认执行父类的构造函数。
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!