我正在学习 OOP,在这里遇到了一点问题,即不理解代码。
这里是。
class ShopProduct {
private $title;
private $producerMainName;
private $producerFirstName;
protected $price;
private $discount = 0;
function __construct( $name, $firstName, $mainName, $price) {
$this->title = $name;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
public function getProducer() {
return "{$this->producerMainName} "."{$this->producerFirstName} \n ";
}
public function setDiscount($num){
$this->discount = $num;
}
public function getDiscount() {
return $this->discount;
}
public function getTitle() {
return $this->title;
}
public function getPrice() {
return ($this->price - $this->discount);
}
public function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
return $base;
}
}
class CDProduct extends ShopProduct {
private $playLength = 0;
public function __construct($title, $firstName, $mainName, $price, $playLength) {
parent::__construct($title, $firstName, $mainName, $price);
$this->playLength = $playLength;
}
public function getPlayLength() {
return $this->playLength;
}
public function getSummaryLine() {
$base = parent::getSummaryLine();
$base .= ": {$this->playLength()} minutes";
return $base;
}
}
class BookProduct extends ShopProduct {
private $numPages = 0;
public function __construct($title, $firstName, $mainName, $price, $numPages) {
parent::__construct($title, $firstName, $mainName, $price);
$this->numPages = $numPages;
}
public function getNumberOfPages() {
return $this->numPages;
}
public function getSummaryLine() {
$base = parent::getSummaryLine();
$base .= ": {$this->numPages()} pages";
return $base;
}
}
class ShopProductWriter {
private $products = array();
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
public function write($shopProduct) {
foreach($this->products as $shopProducts){
$str = "{$shopProduct->getTitle()}: "."{$shopProduct->getProducer()}"." {$shopProduct->getPrice()}$ \n";
}
print $str;
}
}
$product = new CDProduct('Song is the rythm','Zyxel','Beatz',50, 60.33);
$write = new ShopProductWriter();
$write->addProduct($product);
$write->write($product);
问题就在这里
class ShopProductWriter {
private $products = array();
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
public function write($shopProduct) {
foreach($this->products as $shopProducts){
$str = "{$shopProduct->getTitle()}: "."{$shopProduct->getProducer()}"." {$shopProduct->getPrice()}$ \n";
}
print $str;
}
}
如您所见,有条件 - 如果对象不是 ShopProduct 类型 - 会出错。但正如您所见,我正在创建 CDProduct 对象。
$product = new CDProduct('Song is the rythm','Zyxel','Beatz',50, 60.33);
$write = new ShopProductWriter();
$write->addProduct($product);
$write->write($product);
它应该显示错误。谁能告诉我我做错了什么?