0
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());

I would like to print(implode("",$laracasts->getStaffMembers()); instead of just var_dump() it. Thanks.

1
  • 1
    If you want to be able to print an object, you'll need to add a __toString method to it. Commented Jun 29, 2017 at 20:36

1 Answer 1

1

Add a __toString "magic method" to your Person class.

class Person
{
    protected $name;

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

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

__toString provides a string representation of the class, so you can use it in string contexts, like echo $person, or echo implode(', ', $laracasts->getStaffMembers());

In this example I just returned the person's name, but you can do more complex stuff in that method as well (formatting, etc.), as long as it returns a string.

Sign up to request clarification or add additional context in comments.

1 Comment

After your answer i did some research and i just added the __tostring method to the Staff class, because i thought the members had to be converted into a string. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.