构造函数是类中的一个特殊函数,当使用 new 操作符创建一个类的实例时,构造函数将会自动调用。
咱们用一个例子:
class testConstrut{
public function __construct(){
echo "start construt ";
}
}
$test = new testConstrut();
输出结果为:
start construt
有一点要注意的是:与java不同php不能同时在一个类中创建多个构造方法,即一个类中只能有一个__construt()方法。
我们试一下写多个构造方法会出现什么样的错误。
class testConstrut{
public function __construct(){
echo "start construt <br>";
}
public function __construct($name){
echo "start construt ".$name."<br>";
}
}
$test = new testConstrut("dd");
输出结果为:
那么问题来了,我们应该如何像java那样重载多个构造函数呢?
通过判断方法个数,然后再__construts函数里进行判断,走不同的分支就可以了。
代码如下(以NbaPlayer类作为例子):
class NbaPlayer{
//球员的属性
public $name; //姓名
public $height; //身高
public $team; //所在球队
public $no; //球衣号
public function __construct(){
$argNums = func_num_args();
if($argNums == 1){
$this->name = func_get_arg(0);
echo "NAME:".$this->name."<br>";
}elseif ($argNums == 3){
$this->name = func_get_arg(0);
$this->team = func_get_arg(1);
$this->no = func_get_arg(2);
echo "NAME:".$this->name." TEAM:".$this->team." NO:".$this->no."<br>";
}
}
}
$curry = new NbaPlayer("Stephen Curry","Golden State Warriors","30");//创建库里实例
$kobe = new NbaPlayer("Kobe Bryant");//创建科比实例
)
输出结果为:
NAME:Stephen Curry TEAM:Golden State Warriors NO:30
NAME:Kobe Bryant