Declare An Object In PHP
Code snippet for how to Declare An Object In PHP with sample and detail explanation
Objects in PHP create a way to group related data and functions into a single unit. They are instances of classes, which act as blueprints, enabling you to generate multiple objects with the same behaviors.
Code snippet
Let’s consider that we want to create a simple object for a car.
<?php
class Car {
public $color;
public $model;
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$audi = new Car();
$audi->set_color("blue");
?>
Code Explanation
First, we need to define a class to create an object. The keyword class
is proceeded by the name of the class that is Car
, which is followed by a pair of curly braces {``}
.
Inside the class, we have two properties: $color
and $model
are public properties meaning they can be accessed anywhere in the program.
Next, we have two methods within the class. set_color($color)
is a method used to set the color property of the car, while get_color()
would return the color of the car. The $this
keyword refers to the current instance of that class, therefore, $this->color
refers to the color of the car for the specific object.
Lastly, we create an instance of the Car
class by using the new
keyword followed by the class name. This instance is stored in the audi
variable.
To set the color of the audi
object to “blue”, we call the set_color
method on the audi
object.
This is a simple introduction to creating and declaring an object in PHP. With objects, your code can become more modular, reusable and easier to maintain as the complexity of your projects start to grow.