我一直在阅读 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();