PHP Static vs Instance

I'm just about to write a method for converting some billing data into an invoice.

So say that I have an array of objects that contain the data needed to create the invocie elements.

In the billing controller Which of the following methods is correct:

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

Then in the class of accounts

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

OR

Invoice::createInvoiceFromBilling($billingItems)

Then in the class of accounts

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

How is this the right way?

Hello

+4
source share
2 answers

As Tereshko pointed out in the comments section above, you should study the Factory pattern . A good (and simple) real world based example from a related 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 the Automobile instances.

+2

, , , - , .

-1

All Articles