通过类型提示对象获取类中私有 var 的值,以在 PHP 5.3 中分配它


get value of private var in a class through typehinted object to assign it in php 5.3

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

麻烦的是创建一个语句,我需要使用 Movie 类的方法 getCode() 访问一个值(参见开关),因为$code是私有的。(当然,如果所有变量都是公开的,下面的代码就可以工作,但我想将它们保密。

有人可以阐明一下我将如何从语句()中的开关访问调用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();

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

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

当然,您可以将变量保留为 each 。在这种情况下,我只是觉得$movie更具可读性和可理解性。

将您的

行替换为:

$each->getMovie->getCode()