Create class properties in earlier PHP versions
Learn how to define and initialize class properties to store data within objects in earlier PHP versions.
Lesson Content
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 string $name;
public function __construct($name)
{
$this->name = $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 string $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;
public function __construct($name)
{
$this->name = $name;
}
}
You can define as many properties like this as you wish.
Code Diff
diff --git a/classes/Author.php b/classes/Author.php
index 9be618e..67181da 100644
--- a/classes/Author.php
+++ b/classes/Author.php
@@ -2,8 +2,10 @@
class Author
{
+ public string $name;
+
public function __construct($name)
{
- var_dump($name);
+ $this->name = $name;
}
}
<?php declare(strict_types=1);
class Author
{
public string $name;
public function __construct($name)
{
$this->name = $name;
}
}
<?php declare(strict_types=1);
class Author
{
public string $name;
public function __construct($name)
{
$this->name = $name;
}
}
+
<?php
declare(strict_types=1);
class Foo
{
public string $name;
public function __construct($name)
{
$this->name = $name;
}
}
Join the discussion!
Comments
Want to comment on this lesson?
Log in to leave comments.