Data and Logic Together: Constructors in PHP

A class can have a special method, called a constructor, which is run when the object is created. Constructors typically handle setup and housekeeping tasks that make the object ready to use. For example, we can change the Entree class and give it a con­structor. This constructor accepts two arguments: the name of the entree and the ingredient list. By passing those values to the constructor, we avoid having to set the properties after the object is created. In PHP, the constructor method of a class is always called          construct(). Example 6-5 shows the changed class with its construc­ tor method.

Example 6-5. Initializing an object with a constructor

class Entree {

public $name;

public $ingredients = array();

public function _ construct($name, $ingredients) {

$this->name = $name;

$this->ingredients = $ingredients;


public function hasIngredient($ingredient) {

return in_array($ingredient, $this->ingredients);



In Example 6-5, you can see that the construct() method accepts two arguments and assigns their values to the properties of the class. The fact that the argument names match the property names is just a convenience—the PHP engine doesn’t require that they match. Inside a constructor, the $this keyword refers to the specific object instance being constructed.

To pass arguments to the constructor, treat the class name like a function name when you invoke the new operator by putting parentheses and argument values after it. Example 6-6 shows our class with the constructor in action by creating $soup and $sandwich objects identical to what we’ve used previously.

Example 6-6. Calling constructors

// Some soup with name and ingredients

$soup = new Entree(‘Chicken Soup’, array(‘chicken’, ‘water’));

// A sandwich with name and ingredients

$sandwich = new Entree(‘Chicken Sandwich’, array(‘chicken’, ‘bread’));

The constructor is invoked by the new operator as part of what the PHP engine does to create a new object, but the constructor itself doesn’t create the object. This means that the constructor function doesn’t return a value and can’t use a return value to signal that something went wrong. That is a job for exceptions, discussed in the next section

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *