1. 38
    Create & instantiate a class in PHP
    2m 13s

Create & instantiate a class in PHP

Mark Shust
InstructorMark Shust

Share this video with your friends

Send Tweet
Published 8 months ago
Updated 8 months ago

Creating a class in PHP is quite easy with the "new" keyword, and can represent a specific data entity or functionality.

Instructor: [0:00] A great way to structure your code once it gets more and more complex is to use PHP classes. Classes allow you to organize and co-locate multiple functions of business logic together into a unified entity.

[0:16] Let's go ahead and create a new folder for our classes, and we will name this directory classes. Then within it, we will create a new file named Author.php. Make sure the Author has a capital A. It's best practice to name all of the file names for classes with a capital letter.

[0:40] Next, let's go ahead and open a PHP tag and we will declare strict types. Next, we will use the class keyword followed by the name of our class, which is Author. Then what follows is an open and closed curly bracket.

[0:59] This is a class. Nothing else is going on within it, but it is a full class that represents an Author entity. Now, we will include this class in our functions.php file. After this declare strict_types tag at the beginning of our file, let's go ahead and add a require statement, and we will be requiring this file in classes/Author.php.

[1:29] PHP instantiation happens with a special keyword called new. When we follow new with the class name we'd like to create followed by parentheses, when PHP parses the code, it will create a new object that is an instance of this new class that we created.

[1:48] Within getPosts, let's go ahead and create a new author variable, and we will set it equal to new Author, which is our class name.

[1:59] At the moment, this code is just creating a new instance of this author object and assigning it to the author variable. This variable now holds a reference to this newly created object.