PHP Static vs Instance

2019-06-28 08:29发布

问题:

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

回答1:

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.



回答2:

The method written first is better because in the second your code will generate object for invoice each time it is being called.