Create class properties in previous versions of PHP

We now have value passed to constructor, but a var_dump won’t really be doing anything for us. We need to assign this value to a variable. In classes, you do this with something called a class property.

You can think of classes as representing a specific entity, and properties represent values related to that entity. Just like in this example, the Author is an entity, and the author name would be a good property. We can also have other properties like gender, age, location, & so on.

This lesson covers class properties in versions of PHP before 8. I included it first though because it will help you understand how scope & properties work within classes.

You create a class property by using a scope keyword right at the start of a class. We will get into scopes in a later lesson, but for now we will just use the public scope. Next comes the name of the property, and this will be a variable name. So lets name this $name.

<?php declare(strict_types=1);

class Author
{
    public $name;
    ...

Next, we will update our constructor to assign it to this property. First we will use the $this keyword. This keyword references the class you are within. So $this is the specific instance of this Author class. Next, we will use an arrow with a property name, to reference the specific class property. Finally, we can just set this value equal to the argument name.

<?php declare(strict_types=1);

class Author
{
    public $name;

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

It’s always a good idea to also cast your class properties to a specific type. You can do this right after the scope keyword. So right after public, lets cast this $name property to a string.

<?php declare(strict_types=1);

class Author
{
    public string $name;
    ...

You can define as many properties like this as you wish.

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