OOP (有益な使用法)のように、ショッピング カードのアイテムの請求書を作成する場合、Bill オブジェクトをバスケットの handleInvoice() 関数に渡します (すべて PHP で記述されています)。
class Basket {
// -- other code
public function handleInvoice( Bill $invoice ) {
$invoice->chargeFor( $this->items );
$invoice->chargeTo( $this->account );
return $invoice->process();
}
}
これまで請求データが存在しないため、Bill クラスにはコンストラクターは必要ありません。
しかし、以前の請求書の管理にも同じ Bill クラスを使用したい場合は、データベースからすべての請求データをロードするコンストラクターが必要です。
class Bill {
private $date;
// --- other stuff
function __construct( $bill_id ) {
$result = mysql( "select * from invoices where id = $bill_id" );
$this->date = $result['date'];
// --- other stuff
}
}
前者の場合はコンストラクターを実行すべきではなく、後者の場合は実行すべきであることをプログラムにどのように「伝える」ことができますか?