Object Oriented Programming in PHP for Beginner Series
Parth Patel
Posted on February 19, 2020
Object-oriented programming is relatively complex topic in php language. Thus, novice programmers find it difficult to understand php oop specially if they don’t have much programming experience.
Object Oriented Programming was introduced from PHP 4 but it (php oops) gained momentum with PHP 5 version. In 5th version, PHP’s Object model was rewritten which allowed more features with better performance and introduced full object model for php classes.
With this tutorial series, you will gain enough knowledge about PHP OOPs or Object Oriented Programming in PHP to start with.
If you want to learn about php frameworks then you can check our guide on Laravel tutorial.
What is Object Oriented Programming?
Object-oriented programming is a programming style based on the concept of objects. It helps developers by preventing reinventing the wheel and make the code easy to maintain as well as scale.
Object Oriented Programming seems confusing at first but when you go deep, you will realise that it is meant to simplify programming.
Why use Object Oriented Programming?
There are various advantages of using PHP OOP over procedural programming in PHP like:
- Re-Usability and Recycling of code :Let’s say you want to create Mercedes car object while your friends want to create Audi car object. You build your objects but you find that both objects have lot of similarities between Mercedes and Audi car like number of tires. The fact is both actually are car. So instead of created those two objects separately from scratch, if you have one car class with generic properties and methods, you can save lot of repetition by reusing and recycling the code.
- Modularity : If you are creating multiple separate classes for different entities, you are making it modular as if you want to fix something, you only have to edit that specific class and not others. This modularity proves helpful in troubleshooting.
- Scalable : Object Oriented Programs are more scalable than structured programs. An object’s interface provides all the information needed to replace the object thus it makes it easy to replace old code or add new code to scale in future.
- Maintenance : Programs needs to be improved on regular basis with many changes. An Object-Oriented program is much easier to modify and maintain than a non-Object Oriented Program.
Understanding Classes and Objects:
What is Class and Object in PHP OOP?
Before we dive further in Object Oriented Programming world, let’s learn about php classes and objects which are the pillars of PHP OOP paradigm.
A class is a programmer-defined data type which contains different types of data as well as different functions.
An object is an instance of a class. Object gets the copy of all the data and functions in the class thus it acts as independent entity.
Let’s understand classes and objects using an example.
Left side of the above image shows car blueprint and right side shows cars created using that blueprint like Mercedes, BMW, Audi etc.
Thus here, Car is a php class which acts like a blueprint and it contains data properties like number of tires, car type, car color etc.
And Mercedes, Audi are known as objects which we created using class ‘Car’.
All the objects were created from same class and thus they have same functions and properties but they may have different values of their properties. For example, in above image, all cars have different values to their color property – Mercedes is green; BMW is blue; Audi is Orange.
What is method and property?
Properties in a class are variables which can store data of different data types. Method is a function defined inside a class.
All the objects instantiated from that class gets copy of that property variable and a copy of all the member functions aka Methods.
How to create class and object?
In class, we will group the code which handles a particular topic. Thus, for naming the class, we should use singular noun like Car which will handle logic about the cars.
The syntax to create class is very easy and straightforward. You have to use class keyword to declare a class followed by the name of the class.
<?php
class Car
{
// Class properties and methods
}
?>
Notes:
- Declare class using keyword class
- Use singular noun and Capitalize the first letter
- If class name contains more than one word then capitalize each word using upper camel case naming convention. For example: JapaneseCar, AmericanCar
- An instance of a class is an object created from existing class.
- The new keyword is used to create an object from class.
Now, you can create an object from class very easily using new keyword.
$bmw = new Car;
Thus putting it all together:
<?php
class Car
{
// Class properties and methods
}
$bmw = new Car;
?>
How to define properties in class?
To add and store data to a class, properties or member variables are used. Properties can store values of data types – string, integer and decimal numbers, Boolean values etc. These are exactly like regular variables but they are bound to the instantiated object and thus you can access the variable only using the object.
Let’s add some properties to the class Car.
<?php
class Car
{
public $color = ‘red’;
public $numberOfTires = 4;
}
$bmw = new Car;
?>
Notes :
- We used public keyword before class property to determine the visibility of the property about which we will discuss later.
- Class property can have default value. Also you can skip the default value.
Here you can see that we added some properties which are necessary for every car object. Obviously, car class needs lot more properties than this but for the tutorial, this is enough.
Now to read any property, access the property using object. For example:
echo $bmw->color;
The arrow (->) is an OOP construct that accesses the properties and methods of a given object.
How to define methods in class?
The PHP functions which are defined in a class are called methods. Methods in PHP OOP are exactly similar to normal php functions.
Let’s create some methods for our Car class.
<?php
class Car
{
public $color = ‘red’;
public $numberOfTires = 4;
public function setColor($val)
{
$this->color = $val;
}
public function getColor()
{
return $this->color;
}
}
$bmw = new Car;
?>
Here we created two methods 1) setColor – which will assign the given parameter to object’s color property and 2) getColor – which will return the value of object’s color property.
Note: $this is used to reference the current object. You can access class properties and methods from within the class using $this keyword.
Now, to use these methods, call these methods using arrow “->”. You need to reference corresponding objects because every instantiated objects have copy of these properties and methods.
Let’s use these newly created methods.
<?php
class Car
{
public $color = ‘red’;
public $numberOfTires = 4;
public function setColor($val)
{
$this->color = $val;
}
public function getColor()
{
return $this->color;
}
}
$bmw = new Car;
$bmw->setColor(“black”);
echo $bmw->getColor();
?>
Notes:
- A code for the method is to be enclosed within a pair of curly braces.
- You need to use one of the keyword public, protected or private to create a class method or property. These are visibility keywords. More about this you will read later.
- If you haven’t used one of the keyword – public, protected or private then default is public.
- You can also access properties and methods of the current instance or object using $this keyword -- $this->color.
Constructor and Destructor
In php there are some methods known as magic methods. Among them, two most important magic methods are __construct and __destruct. These two are methods to create constructor and destructor for the class. Remember, magic methods always start with two underscores.
What is constructor and destructor?
The __construct method is a method which is called by the class when an object is being created. It is used to prepare the new object for use. Constructors can be used to assign parameter values to the object properties.
The __destruct method is a function which is called by the class when an object is being destroyed. It is generally used to clean up memory as object is being destroyed.
We will create a constructor to set value of the Color property.
<?php
class Car
{
public $color = ‘red’;
public $numberOfTires = 4;
public function __construct($color)
{
$this->color = $color;
}
public function setColor($val)
{
$this->color = $val;
}
public function getColor()
{
return $this->color;
}
}
$bmw = new Car(“white”);
echo $bmw->getColor(); //this will print “white” because our constructor assigned value “white” to color property
$bmw->setColor(“black”); // this will overwrite color property to black
echo $bmw->getColor();
?>
In the above example, we created a constructor which accepts one argument for color and sets it to the color property. We also changed our object creation code and passed a value to be set to color property.
Remember, as we created a constructor to override the default php constructor, we need to pass a parameter to the constructor.
If you try -- $bmw = new Car(); it will give error because our constructor expects one parameter.
Now we will create a destructor which will print message when object is being destroyed
<?php
class Car
{
public $color = ‘red’;
public $numberOfTires = 4;
public function __construct($color)
{
$this->color = $color;
}
Public function __destruct()
{
echo "Object is being destroyed";
}
public function setColor($val)
{
$this->color = $val;
}
public function getColor()
{
return $this->color;
}
}
$bmw = new Car(“white”);
echo $bmw->getColor(); //this will print “white” because our constructor assigned value “white” to color property
$bmw->setColor(“black”); // this will overwrite color property to black
echo $bmw->getColor();
?>
Notes:
- The constructor method is a special magic method introduced with PHP 5 which allows to initialize object properties or perform some action at the time of object instantiation.
- The destructor method is a special magic method which allows to perform some actions at the time when object is being destroyed.
- Classes which have a constructor method, executes that automatically when an object is instantiated or created.
- Classes which have a destructor method, executes that automatically when an object is being destroyed.
- The constructor and destructor are not required. Every php class has a default constructor and destructor. If you create a constructor or destructor, the default one is ignored automatically.
- PHP only executes one constructor and one destructor ever.
- The “__construct” and “__destruct” method starts with two underscores.
Assigning visibility in PHP
Previously we discussed to use one of the keywords – public, private and protected when defining property or a method. Public, Protected and Private are three types of visibility in PHP to control access of properties, variables or methods.
- Public: Public method or variable is accessible everywhere.
- Private: If property variable or method is private then it is accessible only from inside the class. For example: if color property of class Car is private then you cannot access it outside the class like – echo $bmw->color; but a method like getColor can access it because it is inside the class.
- Protected: If property variable or method is protected then it is accessible from inside the class or from inside any class which is inherited from this class.
Why we should not use public visibility all the time?
Because it's not at all secure to keep everything public. To make it secure, PHP OOP has introduced these different visibilities.
Let’s discuss an example showing the importance of private or protected visibility in PHP OOP:
Make changes to our Car Class code as shown below:
<?php
class Car
{
private $color = ‘red’;
private $numberOfTires = 4;
public function __construct($color)
{
$this->color = $color;
}
public function __destruct()
{
echo "Object is being destroyed";
}
public function setColor($val)
{
$this->color = $val;
}
public function getColor()
{
return $this->color;
}
}
$bmw = new Car(“white”);
echo $bmw->color; //this will give error because color property is private
echo $bmw->getColor(); //this will print “white” because our constructor assigned value “white” to color property
$bmw->setColor(“black”); // this will overwrite color property to black
echo $bmw->getColor();
?>
As shown in above code, we made properties private to keep them hidden from the outer world. So, if someone tries to access color property using $bmw->color , it will give error.
And that’s why we created two methods getColor and setColor which are also known as getter and setter methods because they act as a intermediary between outer world and private variable.
So if you want to get the value of color, use $bmw->getColor() and if you want to set value of color , use $bmw->setColor(“white”). This is known as encapsulation.
Static Methods and Properties
A static method or property can be accessed without the need instantiating object. Just use class name, scope resolution operator and property or method name.
We already learnt three modifiers – private, protected and public. Static is the fourth access modifier in PHP OOP which allows access to properties and methods without the need to create objects from the classes.
How to create static method and property
To define methods and properties as static, you need to use reserved static keyword.
Let’s see it in our example:
<?php
Class Car
{
private $color = ‘red’;
private $numberOfTires = 4;
public static $country = “Canada”;
public function __construct($color)
{
$this->color = $color;
}
Public function __destruct()
{
echo "Object is being destroyed";
}
public function setColor($val)
{
$this->color = $val;
}
Public function getColor()
{
return $this->color;
}
}
$bmw = new Car(“white”);
echo $bmw->color; //this will give error because color property is private
echo $bmw->getColor(); //this will print “white” because our constructor assigned value “white” to color property
$bmw->setColor(“black”); // this will overwrite color property to black
echo $bmw->getColor();
echo Car::$country;
?>
Here I defined a constant name country with value Canada. Now I don’t need an object to access that constant.
Note:
- To use the static method and properties within the class, use self
Conclusion
PHP OOP brings lot of advantages compared to procedural programming and it provides easier approach to build complex web applications with easier scalability.
Now, you should be comfortable with Object Oriented Programming style and you should have sound understanding of the basic concepts of PHP OOP i.e Object Oriented Programming.
In the next parts, we will learn advanced concepts of PHP OOP, helpful to create highly modular and complex applications.
Hope you liked this tutorial about OOP in PHP. Do you have any questions or confusion? Comment below.
The post Object Oriented Programming in PHP for Beginner Series appeared first on Parth Patel - a Web Developer.
Posted on February 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.