PHP Construct Magic Method

Posted on

What does it do?

The most common of the magic functions, this one is called whenever a class is created,

Why would you use it?

When you are setting up a class and need to do something as soon as the object is created. For example create a user class and set some properties on that user.

class User {

    protected $firstName;
    protected $lastName;    

    public function __construct($firstName, $lastName){
        $this->firstName = $firstName;
        $this->lastName = $lastName;

$user = new User('John', 'Mackenzie');

These properties will now be set and accessible.

  $user = new User("John", "Mackenzie");
  echo $user->firstName;