Object Oriented Programming (OOP) is a programming concept that makes use of classes, objects, methods, and attributes, together with other provisions of the concept, to write program codes that reduce repetition.
Objects in OOP are abstractions of real-life items. So, a class is a larger set of similar objects with attributes or properties, and actions called methods, which these objects can perform together.
Although each object can have its own properties and methods that are unique to them, how do they get the properties of their base class?
You can basically do this in two ways.
One option is to provide the object properties after you create the object from the base class, just like in the code below.
<?php//class definitionclass car{public $name;public $color;function set_name($name,$color){$this->name = $name;$this->color = $color;}function get_name(){return $this->name;}function get_color(){return $this->color;}}//now let's create the object$toyota = new car();$toyota->set_name('Camry','Black');$carName = $toyota -> get_name();$carColor = $toyota -> get_color();echo ' I have a '.$carColor.' toyota '.$carName;?>
We call the set_name
function to manually set the attributes.
However, a large chunk of code can be reduced if we use the second method of initializing the properties. You can use the __construct()
function to set your object properties. Let’s see this method below.
__construct()
functionThis function allows you to create a constructor, which lets you initialize an object’s properties at the same time as the object’s creation.
public function __construct(arg1,arg2,...argn){
//code
}
By creating this constructor function with the __construct
keyword, PHP will automatically call this function whenever you create an object from the class.
Note: The
__construct
function always begins with two underscores (__
).
Let’s rewrite our code above using a constructor.
<?phpclass car{public $carName;public $carColor;//now using the __construct keyword to create the construct function.public function __construct($carName, $carColor){$this->name = $carName;$this->color = $carColor;}function get_CarName(){return $this->name;}function get_CarColor(){return $this->color;}}$toyota = new car('Camry','Black');echo 'This is a '. $toyota->get_CarColor().' ';echo $toyota -> get_CarName().' Car';
From the sample code above, we can see that using a constructor prevents us from calling the set_name()
method, which reduces the amount of code.