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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!