通过typehinted对象获取类中私有var的值,以在php 5.3中分配它

时间:2012-06-13 19:22:54

标签: php php-5.3 type-hinting

我一直在阅读Martin Fowler的Rafactoring,在本书的开头他使用了一个示例应用程序(用Java编写),我试图将其转换为PHP用于培训目的。 (我已经修改了代码以提出这个问题,但如果变量是公共的,它就可以工作。)

问题是创建一个语句我需要使用Movie类的方法getCode()来访问值(请参阅switch),因为$ code是私有的。 (当然,如果所有变量都是公开的,下面的代码都可以使用,但我希望将它们保密。)

有人可以说明如何从statement()中的switch中访问调用Movie的getCode()方法的私有变量。 (或者,如果有更好的方法,请告诉我。)

class Movie {
    private $title;
    private $code;

    public function __construct($title, $code) {
        $this->title = $title;
        $this->code = $code;
    }

    public function getCode() {
        return $this->code;
    }

    public function getTitle() {
        return $this->title;
    }
}

class Rental {
    private $movie; // will carry a Movie object
    private $days;

    public function __construct(Movie $movie, $days) {
        $this->movie = $movie;
        $this->days = $days;
    }

    public function getMovie() {
        return $this->movie;
    }
}

class Customer {
    private $name;
    private $rentals; // will be a collection of Rental Objects

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

    public function addRental(Rental $rental) {
        $this->rentals[] = $rental;
    }

    public function statement() {
        $thisAmount = 0;

        foreach ($this->rentals as $each) {
            // what is the better way to call this value??????
            switch ($each->movie->code) {
                case 1:
                    $thisAmount+= ($each->days - 2) * 1.5;
                    break;

                case 2:
                    $thisAmount += $each->days * 3;
                    break;

                case 3:
                    $thisAmount += 1.5;
                    break;
            }

            // show figures for this rental
            $result = "\t" . $each->movie->title . "\t" . $thisAmount . "\n";
        }

        return $result;
    }
}

// pick a movie
$movie = new Movie('Star Wars', 0);
// now rent it
$rental = new Rental($movie, '2');

// now get statement
$customer = new Customer('Joe');
$customer->addRental($rental);

echo $customer->statement();

2 个答案:

答案 0 :(得分:3)

您正在迭代您的foreach中的movie集合。所以你可以这样做:

foreach($this->rentals as $rental) {
   switch($rental->getMovie()->getCode()) {

当然,您可以保留名为each的变量。在这种情况下,我发现$movie更具可读性和可理解性。

答案 1 :(得分:1)

只用以下代码替换你的行:

$each->getMovie->getCode()