Explain STATIC AND INSTANCE method in PHP.


In PHP, instance methods are the preferable practice over static methods. In any case, it isn't to say that static methods are not helpful, they have a distinct and unique purpose. Here we discuss a comparison between static and instance methods in PHP.

Here Note that instance method is always connected to the object of the class while on the other hand static methods always connected with the class.

First talk about static method. The static method in PHP is the same as other Object Oriented Programming Languages. Important cases for using the static method in PHP.The static method required to be utilized just when specific information stays steady for the entire class. Essentially, the static method is utilized when to access that method without the help of the object of that class.

Example

<?php
   class Car{
      static function getColor(){
         return "blue";
      }
   }
   echo (Car::getColor());
?>

Output:

blue

Explanation:

For instance,think in the above program some programmer is making the information about a car and in that you have a Car class and have a function getColor() that defines the color of the car ,so each object that needs getColor() function that returns the similar color for all objects of the Class Car,So in this case we can made getColor() method as static.

Let's discuss the Instance Method. An instance method is utilized when there is no way to call the method without creating the object. Also every time the method needs to interact with the properties of the class we required an instance method.

Example

Let's exhibit the above case with an example:

<?php
   class Employee{
      private $empname;
      function setEmpname($empname) {
         $this->empname = $empname;
      }
      function getEmpname() {
         return $this -> empname;
      }
   }
   $obj = new Employee;
   $obj -> setEmpname("Alex");
   echo $obj -> getName();
?>

Output:

Alex

Explanation:

Consider an Employee class in which setEmpname() reads the employeename and getEmpname() method which returns the name of Employee. In this case, every employee name is different from one other so we can't declare either getEmpname() or setEmploye() method as static because every time these methods interact with a variable "$empname".

Updated on: 31-Dec-2019

515 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements