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.
OOP Case
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.
Define a Class
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:
Syntax:
<?php
class Fruit {
// code goes here...
}
?>
Below we declare a class named Car consisting of two properties ($brand and $color) and method startEngine():
<?php
classCar {
// Properties (variables)
public $brand;
public $color;
// Method (function)
publicfunctionstartEngine() {
return"Engine started!";
}
}
?>
Note
In a class, variables are called properties and functions are called methods!
Define Objects
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:
<?php
classCar {
public $brand;
public $color;
// Methods
publicfunctionset_brand($brand) {
$this->brand = $brand;
}
publicfunctionget_brand() {
return $this->brand;
}
}
// Creating objects with constructor
$car1 = new Car();
$car2 = new Car();
$car1->set_brand("Honda");
$car2->set_brand("Ford");
echo $car1->get_brand(); // Output: This is a Honda.
echo"<br>";
echo $car2->get_brand(); // Output: This is a Ford.
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:
Example
<?php
classCar {
public $name;
}
$car = new Car();
?>
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):
We use cookies and similar technologies to enhance your browsing experience, serve personalized content and advertisements, and analyze our traffic.
By clicking "Accept All", you consent to our use of cookies and the processing of your personal data for these purposes.
You can manage your preferences or learn more in our
Privacy Policy and
Cookie Policy.