Understand the concept of PHP traits with examples

 What is PHP Traits?

The concept of Traits is introduced in PHP 5.4, which is basically a group of functions which can be used in any other classes.

To overcome the problem of Multiple Inheritance, PHP introduced traits which is very much welcomed by PHP community.

It let you reuse your code in the much better way. And the combination of Traits and Classes are great when it is used in real programming because it reduces the complexity of code which arises due to the use of the Single Inheritance.

How can we create a Trait in PHP?

Syntax to create a trait in PHP:

1
2
3
4
5
trait MyFirstTrait{
public function traitMethod1(){
// code to do something
}
}

How can we use Trait Method inside a Class?

Traits Methods can be used in Class by using use keyword.

Syntax to use traits in class:

1
2
3
4
5
6
class SampleClass{
use MyFirstTrait; // use already created traits as above
public function classMethod(){
$this->traitMethod1();
}
}

Can we use more than one trait in a single Class?

Yes we can use multiple traits inside a single class

Sample code to use Multiple Traits :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
trait MyFirstTrait{
public function traitMethod1(){ 
echo "traitMethod1";
} 
}
trait MySecondTrait{
public function traitMethod2(){ 
echo "traitMethod2";
} 
}
class SampleClass{ 
use MyFirstTrait, MySecondTrait; 
public function classMethod1(){ 
$this->traitMethod1(); 
}
public function classMethod2(){ 
$this->traitMethod2(); 
} 
}

What if two traits contain methods of same name?

If two traits contain methods of same name then PHP will throw fatal error.

We can solve this condition by resolving the conflict using insteadof keyword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
trait MyFirstTrait {
public function traitMethod() {
echo 'Hello World1!';
}
}
trait MySecondTrait { 
public function traitMethod() {
echo 'Hello World2!';
}
}
 
class SampleClass{
use MyFirstTrait, MySecondTrait{
MyFirstTrait::traitMethod insteadof MySecondTrait;
}
 
public function classMethod(){
echo $this->traitMethod();
}
}
 
$sampleObj = new SampleClass();
$sampleObj->classMethod();

Can a trait use another trait?

Yes, we can use a trait inside another trait.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
trait MyFirstTrait{
public function traitMethod1(){
echo "traitMethod1";
}
}
trait MySecondTrait{
public function traitMethod2(){
echo "traitMethod2";
}
}
trait MyThirdTrait{
use MyFirstTrait, MySecondTrait;
}
class SampleClass{
use MyThirdTrait;
public function classMethod1(){
$this->traitMethod1();
}
public function classMethod2(){
$this->traitMethod2();
}
}
 
$sampleObj = new SampleClass();
$sampleObj->classMethod1();
$sampleObj->classMethod2();

Some more points to remember while using Traits

1
2
3
trait MyFirstTrait{ 
public function traitMethod1();
}
  • We can change the visibility of traits methods inside a class where we are using traits.
1
2
3
4
5
6
trait MyFirstTrait{ 
public function traitMethod1(){// do something};
}
class SampleClass{
use MyFirstTrait{ traitMethod1 as protected;}
}
  • We can also define a variable inside traits which can be used by a class.
1
2
3
trait MyFirstTrait{ 
public variable1 = "Hello World";
}

Traits are not to allowed to instantiate, It can be used with class only. But using too many traits with a class, it will increase the unnecessary responsibilities of a class which is not needed and not desirable for the coding standard.  I hope you enjoyed the articles. Please comment if you like the articles

Understand the concept of Interface in PHP

What is Interface?

An Interface contains methods without body i.e {}. Means, there we get only the declaration of the function, not the definition of the function.

A class which uses interface have to implement all of its methods declared in the interface.

Interface restricts the user to define all the method declared in the Interface in a class, which uses the interface.

How can we define an Interface?

In PHP we can define an Interface using interface keyword before the interface name as we defined below

interface MyFirstInterface{
// required code
}

Interface can have only Abstract Methods and Constant Variables

interface MyFirstInterface{
 const CONSTANT1 = 25; // contant variable
const CONSTANT2 = 50; // constant variable
public function method1();   // Abstract Method
}

How can we use Interface?

The interface can be used by the class using implements keyword.

public class MyClass implements MyFirstInterface{
   public function method1(){
// body of method1
}
}
public class MyClass implements MyFirstInterface, MySecondInterface{  
public function method1(){ 
// body of method1
} 
}
// MyFirstInterface and MySecondInterface are interface here.

This how we can use multiple interfaces at once with a Class.

The interface can be used by another interface using extends keyword.

public interface MySecondInterface implements MyFirstInterface{   
        public function method2(); // abstract method;
}

Why Should we use Interface?

When you want some user who uses your code, should implement some method according to their need which will be customizable by the user. And you want user must implement specific methods. which will be needed by your code.

In these case, you need to define Interface which will restrict the user to implement these methods.

For example:

You are creating Article Publishing Workflow. So to restrict the user to implement compulsory methods in their ArticleWorkflow Class you will need to create an interface.

interface Workflow{
public function draft();
public function sendForReview();
public function sendForPublished();
}

This workflow can be used in Article Publishing Class or Image Publishing Class or Video Publishing Class etc. So Whenever you need to create a workflow you just need to implement this interface only, then this interface will decide the what method should be implemented while creating a workflow class. So by defining the workflow interface you just created a standard process to introduce a New Workflow in the system.

I hope you found this post useful and Happy Learning.

 

 

Concept of Abstraction in PHP

We have completed the understanding of Encapsulation and Inheritance. Now let’s move on to the concept of Abstraction in PHP.

So how can we define Abstraction?

In one way hiding unnecessary details or implementation about the functionality from the user is called  Abstraction.

For Example:-

We all use the functionality of mobile phones like a phone call, send a message, play video etc. But we don’t the implementation of these features on a hardware level and software level. We just use these functionalities without taking care of others things. So here is an Abstraction between the User and the implementation of the functionality.

Why is it important to have this in our programming?

Let’s assume A developer has written a code let’s say, for sending an email. So the developer has written thousands of line of code to send an email. Now, this code is running properly and we are able to send our email. Now do we need to know the code and the meaning of each line of code for sending an email or we just need to call the functionality for sending the email. Which is good and time saver. You Decide!!

So how can we achieve the Abstraction in PHP

We can implement Abstraction in PHP by using concepts below:-
  1. Abstract Classes

Using above example of implementing the functionality of email sending. Now a developer has developed the code to implement the functionality. But for sending an email you will need some input from the user who uses that code. So to restrict that user PHP has the abstract method inside the abstract class. So the developer will write sending email process code inside an Abstract Class.

Abstract Class

A class having one or more abstract method as its member function is called an Abstract Class.

abstract class Shape2d{
public $length;
public $width;
public $sides; public function setLenth();
public function setWidth();
public function setSides();
public function calculatePerimeter(){
// code to calculate perimeter of shapes
} 
} //This is how we define an Abstract Class

 

Some points are required to remember while using Abstract Function:

1. Abstract Class cannot be instantiated.
2. Concrete Class is required to be implemented to use Abstract Class.
3. Abstract Class has to be inherited using “extends” keywords.
4. Abstract is a generalized concept of implementation of Concrete Class.

 

 

Concept of Inheritance in PHP

It is one of the important programming principle in OOPs Concepts. It will let you to code in a more modular way by which you will be able to reuse your code. It introduces the parent and child class concepts in programming language. To implement the inheritance in PHP we use “extends” keyword.

For example, we have two class

  1. Person
  2. Employee

Now let’s decide the relationship between these two classes.

Here Person Class is parent class and Employee is a child class

Person Class is parent class because it shows more primitive information as comare to Employee class.

For example

what a Person Class shows us:-

  1. Gender : male/female.
  2. Name.
  3. Address.
  4. color.
  5. height.

What a Employee Class shows us:-

  1. Gender : male/female
  2. Name
  3. Address
  4. color
  5. height
  6. employee id
  7. employee department
  8. employee salary

These two classes are just for example otherwise it will show much information.

So let’s take close look at employee class here Gender, Name, Address, Color, Height are common with person class. So why do we define it again in Employee, it’s not good programming practice. So what we will do in this case

We define an Employee Class with three attributes only as below mentioned:-

  1. employee id
  2. employee department
  3. employee salary

And others will be inherited from Person Class.

How can we implement inheritance in PHP

class Person{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
}
class Employee extends Person{
public $employee_id;
public $employee_dept;
public $employee_sal;
}
$employee = new Employee();
var_dump($employee); // try this;

Types of inheritance possible with PHP

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance

Single Inheritance :

Single Inheritance consists of a single parent class and will have one child class. This kind of relationship comes from single inheritance. Above mentioned relationship between Person and Employee class is also an example of Single Inheritance.

Multilevel Inheritance :

Multilevel inheritance will have a chain of single inheritance. For example, there is parent and child relationship between Person and Employee class, Now If we define a Manager class which will inherit the employee class. Then this type of inheritance will create a Multilevel Inheritance.

class Person{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
}
class Employee extends Person{
public $employee_id;
public $employee_dept;
public $employee_sal;
}
class Manager extends Employee{
public $department;
public $manager_id;
public $reporting_manager;
}
$mgr1 = new Manager();
var_dump($mgr1); // try this;

Hierarchical Inheritance :

Hierarchical inheritance consists of a single parent class and that parent class is inherited by multiple child class. For Example, there is a parent class named Person and we have two child class named Employee and Student. Both these class inherit Person class. This type of the relationship comes from hierarchical inheritance.

Try out yourself for Hierarchical Inheritance.

 

Inheritance in PHP
Inheritance in PHP

Note:

  1. Multiple Inheritance is not supported in PHP
  2. We cannot use extend keyword with Final Class.
  3. Inheritance represents the IS-A relationship. For Example “Employee is a Person”.
  4. we access parent class property inside child class using parent keyword.
  5. For Interfaces, we use implement keyword to inherit its property.

Inheritance facilitates the code reusability feature which makes it one of the most important principles of OOPs Concepts.

Concept of Encapsulation in PHP

PHP Encapsulation

Wrapping up of the data into a single unit is called Encapsulation in Object-Oriented Programming Languages. Many people get confused when someone asked them to explain it with some examples. This Concept will come in your way every time when you go for an interview.

So now let’s understand the concept of Encapsulation in OOPs in detail.

Meaning of

Wrapping up of the data into a single unit

It means defining Class Member Variables and Member function inside the class. So when we create a class and define some member variables and function inside the class it becomes a single unit which will be known by the class name together.

This small statement has a very deep meaning.

Why we need Encapsulation?

When we wrap our data into something then it hides details from the user who uses it.

For example: When we create an Object from a Class we don’t know what has been written inside the constructor. How it initializes the value of the member variable, How member function we use through object manipulates the value of the member variables or how it generates the output.

This is the main reason for which we use encapsulation so that unnecessary details should be hidden from users who use the class. To achieve this we often make Member Variables private, So that it cannot be accessed outside the class and if someone wants to access these variable, it should be through the GETTER and SETTER methods.

Example of Encapsulation:-

class Person{
private $name;
public $gender; 
public $address; 
public $height; 
public $color; 
public $race; 
public function __construct($name){ 
$this->race = "human"; 
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function setName($name){
$this->name = $name;
}
}

So due to Encapsulation, we are able to achieve Data hiding in OOPs.

So finally the concept of Encapsulation in PHP is hiding internal information of an object to protect from the other object.

This is the simple example of encapsulation with the use of Person Class. But sometimes overuse of inheritance undermines encapsulation in Object Oriented Programmings which we need to take care.

Reference from Wikipedia:

Because inheritance exposes a subclass to details of its parent’s implementation, it’s often said that “inheritance breaks encapsulation”

Gang of Four, Design Patterns
In next articles, we will discuss Inheritance and their types supported by PHP.