Run code on PHP class creation with a constructor

We can execute a bit of code that runs at the time objects are created, with a special piece of functionality called a constructor. This is a built-in PHP feature using what’s known as a magic method, which are always prefixed with two underscores.

Let’s create a constructor by creating a new public function named __construct in our Author class. Within it, we will just dump the output of the string “Author class instantiated”.

classes/Author.php

<?php declare(strict_types=1);

class Author
{
    public function __construct()
    {
        var_dump('Author class instantiated');
    }
}

Now when we reload the page, we will see this message. This magic method executes, or runs every time a new instance of a class is created with the new keyword.

Related to that… functions within classes are referred to as class methods, not functions. So you may hear the terms methods & functions used interchangeably. They are generally the same thing.

We can also pass values into constructors. I’m going to pass my name, Mark Shust, into this class object within it’s parenthesis.

<?php declare(strict_types=1);

require('classes/Author.php');

function getPosts(): array
{
    $author = new Author('Mark Shust');

Next, we will create a method argument to assign it to, which can be any arbitrary value. Let’s name it $name. In this constructor, we will just use var_dump to dump the contents of it out to the screen to make sure it’s working.

<?php declare(strict_types=1);

class Post
{
    public function __construct($name)
    {
        var_dump($name);
    }
}

And when we reload the page, we will see that this output was in fact passed to the constructor, and the var_dump line was executed at the time this object was requested to be created.

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock