Create & instantiate a class in PHP
A great way to structure your code, once it gets more complex, is to use PHP classes. Classes allow you to organize and colocate multiple functions of business logic together into a unified entity.
Create a new file at classes/Author.php
and add create a new Author
class. We will do this with the class
keyword, followed by the name of the class we’d like to create, Author
.
<?php declare(strict_types=1); class Author { }
Now we will include that class with a require statement. Let’s require it in the functions.php
file:
<?php declare(strict_types=1); require('classes/Author.php'); ...
PHP object instantiation happens with a special PHP keyword, new
. When we follow new
with the class name we’d like to create, followed by parenthesis, when PHP parses this code, it will create a new object that is an instance of this class.
<?php declare(strict_types=1); require('classes/Author.php'); function getPosts(): array { $author = new Author(); ...
At this moment, this code is just creating a new instance of this object, and assigning it to the $author
variable. This variable now holds a reference to this newly created object.