PHP静态与实例
发布时间:2020-12-13 22:50:43 所属栏目:PHP教程 来源:网络整理
导读:我只是想写一种方法将一些计费数据转换成发票. 所以说我有一个包含创建invocie项所需数据的对象数组. 而在计费控制器中,以下哪种方式是正确的 $invoice = new Invoice();$invoice-createInvoiceFromBilling($billingItems); 然后在发票类中 Public Function
我只是想写一种方法将一些计费数据转换成发票.
所以说我有一个包含创建invocie项所需数据的对象数组. 而在计费控制器中,以下哪种方式是正确的 $invoice = new Invoice(); $invoice->createInvoiceFromBilling($billingItems); 然后在发票类中 Public Function createInvoiceFromBilling($billingItems) { $this->data = $billingItems; 要么 Invoice::createInvoiceFromBilling($billingItems) 然后在发票类中 Public Function createInvoiceFromBilling($billingItems) { $invoice = new Invoice(); $invoice->data = $billingItems; 哪种方式正确? 问候 解决方法
正如tere?ko在上面的评论部分指出的那样,你应该考虑使用
Factory pattern.来自链接源的一个好的(和简单的)基于真实世界的例子:
<?php class Automobile { private $vehicle_make; private $vehicle_model; public function __construct($make,$model) { $this->vehicle_make = $make; $this->vehicle_model = $model; } public function get_make_and_model() { return $this->vehicle_make . ' ' . $this->vehicle_model; } } class AutomobileFactory { public function create($make,$model) { return new Automobile($make,$model); } } // have the factory create the Automobile object $automobileFactory = new AutomobileFactory(); $veyron = $automobileFactory->create('Bugatti','Veyron'); print_r($veyron->get_make_and_model()); // outputs "Bugatti Veyron" 如您所见,正是AutomobileFactory实际上创建了Automobile的实例. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |