views:

97

answers:

3

PHP: If I have a customer class, and the customer can have a car and an invoice, and I want to have separate car and invoice classes, what is the most efficient way of setting them up?


So, I have three different classes:

customer.class.php

customer_car.class.php

customer_invoice.class.php

What's the best way to set up the relationship/initialization between the three classes? A customer can have a car or an invoice. I want to keep the code separated so that its easy to maintain.

$customer = new customer();
$car = $customer->newCar();
$invoice = $customer->newInvoice();

?

+2  A: 
rockacola
+2  A: 

None of the three classes are related at all. so the simple answer is in the question. Create two variables within the customer class that can hold a car class and an invoice class.

Remember within OOP use the ISA HASA relationships in other words the customer is not a car nor an invoice but the customer has a car and an invoice so in both cases it matches HASA.

The customer ISA person though so you could extend the customer class from a person class.

class customer extends person {
    private $invoice; // variable to hold invoice
    private $car;     // variable to hold car

   ...
}

DC

DeveloperChris
Of course as rockola correctly points out a customer can have multiple of each so you could have arrays holding cars and invoices.
DeveloperChris
+2  A: 

why not

$customer = new customer();
$car = new car();
$invoice = new invoice();

$car->SetOwner($customer);
$invoice->SetCustomer($customer);

Think about adding a new item, such as Payment. How much additional work is necessary with your approach vs. mine. This sounds like a homework problem, so I won't spell it out.

MadCoder