Video Lesson: Run code when creating a class with a constructor in PHP

Run code when creating a class with a constructor in PHP

Learn how to use PHP constructors to run code and initialize objects when they are created.


Lesson Content

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 use var_dump to dump the name passed to the constructor.

classes/Author.php

<?php declare(strict_types=1);

class Author
{

}

Here’s the updated classes/Author.php:

<?php declare(strict_types=1);

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

Now when we reload the page, 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 its parentheses.

<?php declare(strict_types=1);

require('classes/Author.php');

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

    return [
        [
            'title' => 'How to learn PHP',
            'content' => 'This is how you learn PHP.',
        ],
        [
            'title' => 'How to learn MySQL',
            'content' => 'This is how you learn MySQL.',
        ],
        [
            'title' => 'How to learn Nginx',
            'content' => 'This is how you learn Nginx.',
        ],
    ];
}

function getPostText(int $numPosts): string
{
    return $numPosts === 1 ? 'post' : 'posts';
}

Here’s the updated functions.php:

<?php declare(strict_types=1);

require('classes/Author.php');

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

    return [
        [
            'title' => 'How to learn PHP',
            'content' => 'This is how you learn PHP.',
        ],
        [
            'title' => 'How to learn MySQL',
            'content' => 'This is how you learn MySQL.',
        ],
        [
            'title' => 'How to learn Nginx',
            'content' => 'This is how you learn Nginx.',
        ],
    ];
}

function getPostText(int $numPosts): string
{
    return $numPosts === 1 ? 'post' : 'posts';
}

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 Author
{
    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.

Code Diff

diff --git a/classes/Author.php b/classes/Author.php
index 5dd0ad2..9be618e 100644
--- a/classes/Author.php
+++ b/classes/Author.php
@@ -2,5 +2,8 @@
 
 class Author
 {
-
+    public function __construct($name)
+    {
+        var_dump($name);
+    }
 }
diff --git a/functions.php b/functions.php
index 92ff7f4..de54788 100644
--- a/functions.php
+++ b/functions.php
@@ -4,7 +4,7 @@
 
 function getPosts(): array
 {
-    $author = new Author();
+    $author = new Author('Mark Shust');
 
     return [
         [
Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!