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:
<?php class 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 class User { protected $name; protected $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; var_dump($this->name); var_dump($this->age); } } new User; #1 new...