我如何在一个有利的方式使用OOP的问题,我认为作为一个例子篮子到它的主人(汤姆)具有一定ADDRESS(纽约州)可以添加项目(自行车,汽车)。 最后一个法案是印刷方含所有这些信息。
我的问题是:如何处理收集所需信息(这里:主人,城市,量的项目),从几个对象? 因为我认为这是愚蠢的手动执行此操作按以下步骤进行(见图4),不是吗? (更因为信息量实际上增加)
那么,什么是“干净的方式”,用于创建账单/收集在这个例子中所需要的信息?
<?php
$a = new basket('Tom','NY');
$a->add_item("Bike",1.99);
$a->add_item("Car",2.99);
$b = new bill( $a );
$b->do_print();
1。
class basket {
private $owner = "";
private $addr = "";
private $articles = array();
function basket( $name, $city ) {
// Constructor
$this->owner = $name;
$this->addr = new addresse( $city );
}
function add_item( $name, $price ) {
$this->articles[] = new article( $name, $price );
}
function item_count() {
return count($this->articles);
}
function get_owner() {
return $this->owner;
}
function get_addr() {
return $this->addr;
}
}
2。
class addresse {
private $city;
function addresse( $city ) {
// Constructor
$this->city = $city;
}
function get_city() {
return $this->city;
}
}
3。
class article {
private $name = "";
private $price = "";
function article( $n, $p ) {
// Constructor
$this->name = $n;
$this->price = $p;
}
}
4。
class bill {
private $recipient = "";
private $city = "";
private $amount = "";
function bill( $basket_object ) {
$this->recipient = $basket_object->get_owner();
$this->city = $basket_object->get_addr()->get_city();
$this->amount = $basket_object->item_count();
}
function do_print () {
echo "Bill for " . $this->recipient . " living in " . $this->city . " for a total of " . $this->amount . " Items.";
}
}