The __construct method
Learn to run code on instantiation with the __construct magic method.
What is __construct?
When an instance is created from a class, PHP calls a special method automatically: the constructor. In PHP the constructor's name is fixed: __construct. Because it begins with a double underscore, PHP treats it as a magic method.
You declare it as public function __construct(). The moment you write new ClassName(), PHP first builds the object and then calls __construct. This lets you do any setup before the instance is used.
A constructor is not expected to return a value; its job is to make the object ready to use.
Constructor syntax
The constructor is written inside the class like any other method. The only difference is its name: __construct. The general form is:
class User {
public function __construct() {
// setup code
}
}Inside you write code that should run when an instance is born; for example printing a welcome message or opening a file. You cannot rename the method; if you pick a name other than __construct, PHP treats it as a regular method and never calls it on new.
The constructor's visibility is usually public, so the class can be instantiated from outside with new.
Exercise Add a constructor to the User class
Define a class named User. The class should have a __construct method that prints User created to the screen when new User() is called; end the line with \n. Below the class create an instance with $user = new User();. The output should be a single line.
Show example solution
Write the constructor as public function __construct(). In the body add echo "User created\n";. Outside the class call $user = new User();.
Example solution:
<?php
// Define the User class and add a constructor
class User {
public function __construct() {
echo "User created\n";
}
}
$user = new User();
Test yourself
-
When does __construct run?
- When the class is declared, before new is used
- When an instance is created with new, automatically
- When one of the class methods is called
- At program end, when the instance is destroyed
Show answer
When an instance is created with new, automatically — Correct. __construct is called automatically by PHP the moment an instance is created with new.
-
Complete the constructor method name
class Logger { public function ____() { echo "Logger ready\n"; } }Show answer
class Logger { public function __construct() { echo "Logger ready\n"; } } -
Match the concepts
- __construct
- constructor method name
- new
- instantiation operator
- public
- default visibility
- magic method
- magic method category