dongya2030 2015-12-28 22:51
浏览 34
已采纳

为什么数组没有添加到PHP类的属性?

I'm new to OOP PHP and have been following Laracasts OOP Bootcamp. I have reached a certain part of the tutorial where I'm having trouble. I have the following file (ignore that conventions were not followed, as it is the learning phase):

<?php
class Person
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

class Staff
{
    protected $members = [];

    public function __constructor($members = [])
    {
        $this->members = $members;
    }

    public function add(Person $person)
    {
        $this->members[] = $person;
    }

    public function members()
    {
        return $this->members;
    }
}

class Business
{
    protected $staff;

    public function __construct(Staff $staff)
    {
        $this->staff = $staff;
    }

    public function hire(Person $person)
    {
        $this->staff->add($person);
    }

    public function getStaffMembers()
    {
        return $this->staff->members();
    }
}

$jeffrey = new Person('Jeffrey Way');

$staff = new Staff([$jeffrey]);

$laracasts = new Business($staff);
$laracasts->hire(new Person('Jane Doe'));

var_dump($laracasts->getStaffMembers());

Unfortunately, the var_dump is only giving me one staff member:

array(1) {
  [0]=>
  object(Person)#4 (1) {
    ["name":protected]=>
    string(8) "Jane Doe"
  }
}

I have tried adding [] to the line $this->members = $members; under Staff class but it's still giving me the same output. I've also double checked the files, I should be expecting two members instead of one.

Can someone tell me where I went wrong?

Thanks for your time.

  • 写回答

1条回答 默认 最新

  • dongyiyu3953 2015-12-28 23:03
    关注

    Your code is correct except for one line - the constructor for the class Staff is defined incorrectly. Replace

    public function __constructor($members = [])
    

    with

    public function __construct($members = [])
    

    Because of this mistake, the line $staff = new Staff([$jeffrey]); has no effect to the initialization of your internal $members array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题