我正准备编写一个方法将一些账单数据转换成发票。
假设我有一个对象数组,其中包含创建调用项所需的数据。
While in the billing controller 以下哪种方式是正确的
$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"
如您所见,实际创建 Automobile 实例的是 AutomobileFactory。
关于PHP 静态与实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20263322/