PHP __construct (🧙‍♂️Lesson 1: PHP Magic Methods)

cleancodestudio image

Today, we'll quickly cover the most popular PHP magic method - __construct.

__construct magic method

PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Using the PHP __construct magic method

<?php

class User
{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

$timmy = new User('Timmy');


echo $timmy->name;

// "Timmy"
cleancodestudio image
cleancodestudio image

Did you know I have a newsletter? 📬

If you want to get notified when I publish new blog posts or make major project announcements, head over to

58