构造函数 ,是一种特殊的方法。主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。特别的一个类可以有多个构造函数 ,可根据其参数个数的不同或参数类型的不同来区分它们 即构造函数的重载。本文将使用实例讲解php构造函数的使用方法
如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类没有自己的构造函数,那么将默认执行父类的构造函数。