Class Constructors and Magic Methods

The constructor is a special method, added with PHP 5, that is executed when an object is created. A constructor isn’t required, and you don’t need to use a constructor if you don’t want to set any property values or perform any actions when the object is created. Only one constructor is allowed.


The constructor has a special name so that PHP knows to execute the method when an object is created or constructed. Constructors are named __construct (two underscores). Constructors are functions that are invoked when you create a new instance of the class. They look like normal methods, with the exception that their name is always __construct, and that they do not have a return statement, as they always have to return the new instance.

function __construct()
$this->total = 0; // starts with a 0 total

As a constructor is still a function, it can use arguments.

Magic Methods

There is a special group of methods that have a different behavior than the normal ones. Those methods are called magic methods, and they usually are triggered by the interaction of the class or object, and not by invocations. The magic methods start with __ (two underscores ).


This method is invoked when we try to cast an object to a string. It takes no parameters, and it is expected to return a string.


This is the method that PHP calls when you try to invoke a method on a class that does not exist. It gets the name of the method as a string and the list of parameters used in the invocation as an array, through the argument.


This is a version of __call for properties. It gets the name of the property that the user was trying to access through parameters, and it can return anything.


In addition to the constructor, classes can also have a destructor. This magic method starts with two underscores followed by the word destruct. It is called as soon as there are no more references to the object, before the object is destroyed by the PHP garbage collector.

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive