A class is a piece of code describing what we need to save ( properties ) and what kind of operations we need to perform with that saved data ( methods ).

In the last chapter, we saw this image describing that class is like a blueprint. If you are going to build a house, you will need a blueprint. Then, you create your house. In Object-Oriented Programming, considering a class as a blueprint is the easiest way to understand what is it for.

Classes in OOP PHP

Programmatically, a class is a code that is written to handle a specific task. This is your blueprint. You can build multiple houses from this blueprint, but, all of them will have the same properties (with different values) and the same methods. Let's see how to write a class in PHP.

PHP Declaring Classes

The class keyword followed by the class name is used to declare a class.

<?php class House { // code }

Here, class says to PHP that you are going to write a class. House is the name of your class.

All the code of the class will be written inside the braces. In this way, you can wrap all the data and functions of a task inside one class. For instance, in our house class, we can save data like color and functions like change color in the class. You will learn how to do that in the next chapters.

Naming a Class

The name you use for a class ("House" in the above example),

Should not be a PHP reserved word.

Should start with a letter or underscore.

Can have letters, numbers or underscores after the first character.

Best Practices for Naming Classes

Start the class name with an uppercase character.

If you have more than one word, capitalize each word's first letter (ex: TowerHouse, LongHouse, CourtyardHouse)

Using these standards improves the readability of your code. But, those are just standards. If another way works for you, simply use that. You will learn about these standards in a later chapter.

Class Properties and Methods

As you have seen, a class can have properties and methods. In the next chapters, we will learn how to add those into a class to create a meaningful class.