从对象组合中获取数据

时间:2011-11-09 05:09:41

标签: php object

假设我有3个对象:“Place”,“Person”,“Action”。

根据此人的位置和此人的年龄,此人可以采取不同的行动。

例如:

$place->person->action->drive(); // OK if place is "parking" and "person" is 18+
$place->person->action->learn(); // OK if the place is "school" and person is less than 18.

如何从Action类中访问有关“Person”和“Place”对象的数据?

类示例:

class Place {
    public $person;
    private $name;

    function __construct($place, $person) {
        $this->name = $place;
        $this->person = $person;
    }

}

class Person {
    public $action;
    private $name;
    private $age;

    function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
        $this->action = new Action();
    }
}

class Action {
    public function drive() {
        // How can I access the person's Age ?
        // How can I acess the place Name ?
    }

    public function learn() {
        // ... Same problem.
    }
}

我认为在创建Action对象时可以将“$ this”从Person传递给Action(即$ this-> action = new Action($ this)),但是Place数据呢?

1 个答案:

答案 0 :(得分:0)

将Person作为Place的属性或Action属于Person的属性是没有意义的。

我更倾向于为Person和Place的属性创建公共的 getters ,并使它们成为Action的可注入属性,或者至少将它们作为Action的方法的参数传递,例如

class Place
{
    private $name;

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

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

class Person
{
    private $name;
    private $age;

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

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

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

class Action
{
    private $person;
    private $place;

    public function __constuct(Person $person, Place $place)
    {
        $this->person = $person;
        $this->place = $place;
    }

    public function drive()
    {
        if ($this->person->getAge() < 18) {
            throw new Exception('Too young to drive!');
        }

        if ($this->place->getName() != 'parking') {
            throw new Exception("Not parking, can't drive!");
        }

        // start driving
    }
}