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 ...

Get Mastering PHP 7 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.