echo OOP php method


echo OOP php method

我上过一堂OOP课,其中包括类之间的消息传递。在教程中,这个家伙刚刚展示了它的var_dump输出版本。我想玩代码,从var_dump改为echo输出,因为这在将来会更有用。我只是找不到任何解决方案,所以你们是我唯一的选择。这是代码。

<?php
class Person {
    protected $name;
    public function __construct($name) 
    {
        $this->name = $name;
    }
    public function getName()
    {
        return $this->name;
    } 
}
class Business {
    // adding Staff class to Business
    public function __construct(Staff $staff)
    {
        $this->staff = $staff;
    }
    // manual hire(adding Person to Staff) 
    public function hire(Person $person)
    {
        // add to staff
        $this->staff->add($person);
    }
    // fetch members
    public function getStaffMembers()
    {
        return $this->staff->members();
    }
}
class Staff {
     // adding people from Person class to "member" variable
     protected $members = [];
    public function __construct($members = []) 
    {
        $this->members = $members;
    }
    // adding person to members
    public function add(Person $person) 
    {
        $this->members[] = $person;
    }
    public function members()
    {
        return $this->members;
    }
}
// you can also create an array with this method
$bros = [
    'Bro', 
    'Zdenko', 
    'Miljan', 
    'Kesten'
];
// pretty simple to understand this part
$employees = new Person([$bros]);
$staff = new Staff([$employees]);
$business = new Business($staff);
var_dump($business->getStaffMembers());
// or the print_r, it doesn't matter
print_r($business->getStaffMembers());
?>

尝试循环遍历数组并回显每个值。

$array = $something //your assignment here
foreach($array as $key => $value ){
    echo "$key => $value'n";
}