PHP静态与实例 [英] PHP Static vs Instance

查看:44
本文介绍了PHP静态与实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正要编写一种方法,将一些计费数据转换为发票.

I am just about to write a method to convert some billing data into an invoice.

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

So say i have and an array of objects that contain the data necessary to create the invocie items.

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

While in the billing controller Which of the following way is correct

$invoice = new Invoice();
$invoice->createInvoiceFromBilling($billingItems);

然后在发票类别中

Public Function createInvoiceFromBilling($billingItems)
{
    $this->data = $billingItems;

OR

Invoice::createInvoiceFromBilling($billingItems)

然后在发票类别中

Public Function createInvoiceFromBilling($billingItems)
{
    $invoice = new Invoice();
    $invoice->data = $billingItems;

哪种方法是正确的?

致谢

推荐答案

正如tereško在上面的评论部分中指出的那样,您应该使用

As tereško pointed out in the comments section above, you should look into using the Factory pattern. A good (and simple) real-world-based example from the linked source:

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

As you can see, it is AutomobileFactory that actually creates instances of Automobile.

这篇关于PHP静态与实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆