Object-Oriented PHP: The __construct() Magic Method

php magic methods __construct()

In this article, we tackle an intermediate topic in object-oriented PHP: magic methods, specifically __construct().

Our goal in this article is to explain __construct() itself: of all the magic methods in OO PHP, it’s by far the most important, certainly in a WordPress context. To explain _construct(), though, we first need to explain what magic methods themselves are. Let’s dive in.

What Magic Methods Are in Object-Oriented PHP

Recall from our introduction to OO PHP that a method is simply a function defined inside a class:

function functionOne() {
	// I'm a function
}

class myClass {
	function functionTwo() {
		// I'm a method: a function defined inside a class
	}
}

Magic methods are truly methods, in the sense above. There’s only one thing that makes them special among all other methods: The “magic” in magic methods is that PHP will call them automatically in certain circumstances.

In other words, normal methods will never run unless called manually. Let’s look at the code example again:

class myClass {
	function functionTwo() {
		// Behavior
	}
}

// functionTwo() has never been called
$object = new myClass(); // functionTwo() has still never been called
$object->functionTwo(); // Okay, we finally called functionTwo() manually and it will now run

So, what does it mean “PHP will call magic methods automatically?” To answer that we’ll look at __construct() itself. Before we move on from this bare-bones definition of magic methods, three other helpful pieces of information:

  1. All PHP magic methods have defined names. There’s a set stock of them, __construct() and some others, and the names are already set for you.
  2. All PHP magic method names start with two underscores, __. If you see a function inside a class named like __functionname(), it’s most likely a PHP magic method.
  3. There’s an outstanding guide to PHP magic methods and their functionality (with good code examples) here. And, of course, you can always read the PHP official documentation.

That’s a sketch of PHP’s magic methods. Let’s move on to the one we care about: __construct().

__construct(): What it Does

For any PHP class with a __construct() magic method defined, __construct() will be called automatically anytime someone instantiates (creates) an object of that class.

In other words:

class myClass {
	function __construct() {
		// Behavior
	}

	function functionTwo() {
		// Behavior
	}
}

// Both __construct() and functionTwo() have never been called
$object = new myClass(); // __construct() gets called automatically!
//functionTwo() still hasn't been called

To say that again: If you define a __construct() method for a class you’re creating, that method will get called automatically whenever someone creates a new object of that class.

Uses of __construct(): Passing Properties as Arguments on Object Creation

To see what __construct() is good for, let’s return to our tutorial class, Dog. And let’s work simply with one property of the Dog class, color.

class Dog {
    public $color;
}

$lucy = new Dog(); // We made a new Dog, but its color property is not set
$lucy->color = 'brown' // Okay, the new Dog object now has color 'brown'

The first thing we can do with __construct() is more quickly set initial properties of each new object we create. We do that by passing arguments to __construct() in the process of instantiating the object:

class Dog {
	public $color;

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

$lucy = new Dog( 'brown' ); // __construct() runs with 'brown' passed in as its first argument, and so the $lucy Dog has color 'brown'!

How did we do that? “Magic”: because PHP knows it’s running __construct() immediately on object creation, it lets us write arguments in our new statement, and passes them to __construct(). The result is that we can create an object, and define its initial properties, all on one line. That saves us a line of code on object creation, and it’s easy to read and understand as well.

So, most broadly, the arguments you pass in writing new ClassName( $arg1, $arg2 ) go directly to that class’s __construct magic method as $arg1$arg2, and so on.

Uses of __construct(): Setting Default Properties

Imagine there’s a default color for dogs: brown. Dogs are brown unless someone says otherwise. Now, how would you say that with OO PHP?

class Dog {
	public $color;

	// Our __construct method sets Dogs to have color 'brown' by default
	public function __construct( $color = 'brown' ) {
		$this->color = $color;
	}
}
$max = new Dog; // This Dog has color 'brown' 
$clifford = new Dog( 'red' ); // This Dog has color 'red' - overriding the default set in `__construct()`

So __construct() is our way to set default values for a class’s properties: values that each object of that class takes on unless otherwise specified.

__construct() Example in WordPress: The WP_Query Class

To see this in action, let’s look at the source code for the __construct() function of perhaps the most important class in WordPress, the WP_Query class. (We’ve written extensively about WP_Query in our free course on the subject, so have a look there if you’d like to know more.)

The WP_Query class itself is over 4,000 lines of code long(!), but its __construct() method is fairly simple:

    /**
     * Constructor.
     *
     * Sets up the WordPress query, if parameter is not empty.
     *
     * @since 1.5.0
     *
     * @param string|array $query URL query string or array of vars.
     */
    public function __construct( $query = '' ) {
        if ( ! empty( $query ) ) {
            $this->query( $query );
        }
    }

What is this __construct() function doing? It’s what lets you write code like the following:

$args = array( 'posts_per_page' => 20 ); 
$query = new WP_Query( $args );

Have you ever wondered how WP_Query knew what to do with that $args array you were passing in? It was “magic”: the magic of WP_Query‘s __construct() magic method, which takes an array that you pass in during object construction and sets it to be the query property of that object.

And That’s __construct() in Action

As you get more familiar with OO PHP, you’ll see __construct() pop up all kinds of places. This introduction to the topic should explain a lot of the “magic” that makes __construct() so handy, but also potentially confusing.

Thanks for reading! If you have questions or comments, leave them below or say hi in our Facebook group.

Image credit: Ethan Hoover


Add a Comment

Your email address will not be published. Required fields are marked *