PHP OOP Classes
Classes are blueprints.
Class Declaration in PHP
A class wraps a the code that handles a specific task or topic. In this tutorial set we will create houses. So, the class is your blueprint. You can use this blueprint to create different houses. But, all of them will have same properties (with different values) and same methods.
Lets create a class called House.
Here, class is the keyword to say 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.
Naming a Class
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)
Adding Properties to a Class
Classes can have variables within it. Those variables are called properties. A property is a normal PHP variable which is in any data type (integer, string, array, object, etc).
In classes, before declaring a variable we should add the visibility keyword to define where the variable is available. You will learn more about this later. For now, keep in mind that adding public keyword in front of the variable will make the variable available everywhere.
As in the above example, we can declare any type of variable as a property (The value of it is the default value for that variable). Also, note that $extra variable does not have a default value.
For instance, a blueprint can have default widths and heights in it. But, also some houses will need some additional features that are not defined in the blueprint. So, those additional features does not have a default value. But, they can be added to a house.
In the next tutorial, you will learn how to create objects from classes (different houses from our blueprint).