PHP Basic Tutorial
MySQL Connection
PHP Advanced
A class is a blueprint for creating objects. It defines properties (variables) and methods (functions).
An object is an instance of a class. It contains the properties and can execute the methods defined in the class.
Let's assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties.
When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
A class is created using the class
keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:
<?php class Fruit { // code goes here... } ?>
Below we declare a class named Car consisting of two properties ($brand and $color) and method startEngine():
Note
In a class, variables are called properties and functions are called methods!
Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.
An object is created using the new
keyword.
In the example below, $car1and $car2 are instances of the class Car:
Try it yourself
In the example below, we add two more methods to class Car, for setting and getting the $color property:
Try it yourself
In PHP, the $this
keyword refers to the current instance of the class. It is used inside class methods to access properties and methods of the same object.
Look at the following example:
So, where can we change the value of the $name property? There are two ways:
1. Inside the class (by adding a set_name() method and use $this):
Try it yourself
2. Outside the class (by directly changing the property value):
Try it yourself
The instanceof
keyword in PHP is used to check if an object belongs to a specific class or inherits from a particular class.
Try it yourself