class Person
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
}
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();
}
}
class Staff //staff é uma coleção, logo os membros são um array
{
protected $members = [];
public function __construct($members = [])
{
$this->members = $members;
}
public function add(Person $person)
{
$this->members[] = $person;
}
public function members()
{
return $this->members;
}
}
$daniel = new Person('Daniel Santos'); //name==$daniel santos
$staff = new Staff([$daniel]);
$laracasts = new Business($staff);
$laracasts->hire(new Person("Jorge"));
var_dump($laracasts->getStaffMembers());
我想print(implode("",$laracasts->getStaffMembers());
而不仅仅是var_dump()
。感谢。
答案 0 :(得分:1)
在Person
课程中添加__toString
"magic method"。
class Person
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
}
__toString
提供了该类的字符串表示形式,因此您可以在字符串上下文中使用它,例如echo $person
或echo implode(', ', $laracasts->getStaffMembers());
在这个例子中,我刚刚返回了这个人的名字,但你也可以在该方法中做更复杂的事情(格式化等),只要它返回一个字符串。