O'Reilly logo

Mastering PHP 7 by Branko Ajzele

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using __construct()

The __construct() magic method represents a PHP constructor concept similar to that of other OO languages. It allows developers to tap into the object creation process. Classes that have the __construct() method declared, call it on each newly-created object. This allows us to deal with any initialization that the object may need before it is used.

The following code snippet shows the simplest possible use of the __construct() method:

<?phpclass User{  public function __construct()  {    var_dump('__construct');  }}new User;new User();

Both User instances will yield the same string(11) "__construct" output to the screen. The more complex example might include constructor parameters. Consider the following code snippet:

 <?php ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required