php的学习笔记之面向对象(三) 构造函数

构造函数是类中的一个特殊函数,当使用 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kitt15

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值