将类的对象转换为字符串

时间:2017-06-29 20:34:33

标签: php

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()。感谢。

1 个答案:

答案 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 $personecho implode(', ', $laracasts->getStaffMembers());

在这个例子中,我刚刚返回了这个人的名字,但你也可以在该方法中做更复杂的事情(格式化等),只要它返回一个字符串。