简体   繁体   中英

PHP Static vs Instance

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

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);

Then in the Invoice Class

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

OR

Invoice::createInvoiceFromBilling($billingItems)

Then in the Invoice Class

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

Which way is the correct way?

Regards

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"

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM