PHP静态与实例


PHP Static vs Instance

我即将编写一个方法,将一些计费数据转换为发票。

假设我有和一个对象数组,其中包含创建invoice项所需的数据。

在计费控制器中,以下哪种方式是正确的

$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模式。来自链接来源的一个好的(简单的)基于现实世界的例子:

<?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的实例。

首先编写的方法更好,因为在第二个方法中,每次调用invoice时,代码都会为其生成对象。