php-b-grader
php-b-grader

Reputation: 3315

How to create an instance of a class with and without value

I have a class which I use to create a list of customers or a single customer.

I was simply calling new Customer() and then calling the method

customer->setCustomerList()

Then I decided to create a constructor and set an individual customer_id to return just one customer:

public function __construct($customer_id)

now my setCustomerList call throws an error because the new Customer() call is missing the customer_id...

I now get this error:

Warning: Missing argument 1 for Suppliers::__construct()

I know if I pass a value it will work but that's not my question - my question is how do I let the class create an instance without the customer_id? Just an empty instance WHILE ALSO leaving the constructor to create an instance with a custoemr_id?

Upvotes: 1

Views: 95

Answers (2)

Finbarr
Finbarr

Reputation: 32126

public function __construct($customer_id = NULL)

Gives a default value when none is passed.

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400952

Modify the declaration of your constructor so the parameter is optional, with a default value :

public function __construct($customer_id = null)

Then, inside your constructor :

  • if $customer_id !== null, use that parameter, as a value has been passed.
  • else, it has not been passed as a parameter -- and, so, don't try to use it.


The relevant section of the manual : Default argument values

Upvotes: 4

Related Questions