In this article I am going to show you how to create class and objects from that class in details. But before that if you want to just quickly review the OOP concepts, checkout my following article.
I have discussed OOP in PHP in this following article:
Let’s start with the situation in a real world.
We have different types of cars in real world. Now a car can have properties like color, brand, model name etc and there are many types of cars as well and there are many types of brands and colors and all. So, if we create a class named Car, their objects can be different types of car for example sedan, SUV etc or different types of brands like Toyota, Tesla etc. Now, if you select brand name as object then the type of car will become a property of the car. For example, Toyota object of Car class has a cat_type property.
Let’s Define A Class
In PHP we use class keyword to define a class and then followed by the name we want to give it to the class and then pair of curly braces (just like PHP functions). All related information like its properties and methods will be inside the curly braces.
Class name is case-sensitive.
Properties are nothing but variables and methods are nothing but functions.
Take a look at the syntax:
class Car{
// properties or variables
....
....
//methods or functions
.....
}
Let’s look at the example.
Let’s create a class with the name Car and set its properties.
//code inside PHP file
class Car{
// Define Properties
public $name;
public $color;
// Define Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
Now, let’s define objects of a Car class.
Now, we have a class named Car, we can have many different types of car. Just change the properties and you’ll have a different car.
But before that we need to create different objects for the class Car and set their properties.
We use new keyword to create new objects.
class Car {
// Define Properties
public $name;
public $color;
// Define Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$Tesla = new Car();
$Toyota = new Car();
$Tesla->set_name('Tesla Model 3');
$Toyota->set_name('Toyota Camry');
$Tesla->set_color('Black');
$Toyota->set_color('Red');
echo "I have " . $Tesla->get_name() . " and " . $Toyota->get_name() . ".";
echo "<br>";
echo "<br>";
echo $Tesla->get_name() . " has " . $Tesla->get_color() . " color and " . $Toyota->get_name() . " has " . $Toyota->get_color() . " color.";
In the example above, I have made two instances of a class Car. One is $Tesla and the other one is $Toyota. After that, I have set names and colors for $Tesla and $Toyota.
Now that everything is set we can call the properties of those objects and print it out using echo or print.
basics class object-oriented objects