Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

In php what is the use of declaring a member method as static?

when a regular member method can be accessed directly using its class name i.e without instantiating the class... plz answer in the context of php only.

user-image
Question added by Rashid Anwar , senior php developer , sparx it solution pvt ltd.
Date Posted: 2013/09/22
Imranullah Khan
by Imranullah Khan , Full Stack Developer , GoDigital Inc

You can use static keword to declare a function as static. You can see the difference between static function and member function in below code. In non-static function case we use an object to invoke a function while in staic case we use class name directly to call or invoke a function.class test {publicfunction sayHi($hi ="Hi"){ $this->hi = $hi;return $this->hi;}}class test1 {publicstaticfunction sayHi($hi){ $hi ="Hi";return $hi;}}// Test $mytest =new test();print $mytest->sayHi('hello');// returns 'hello'print test1::sayHi('hello');// returns 'hello'

islam khalil
by islam khalil , Technical Manager , iCloudit

To access class method or variable without making instance of this class .

Nouphal Muhammed
by Nouphal Muhammed , Senior Web Developer , Planet Green Solutions

The use of declaring a member method as static depends on the situtation and functionality you are about to implement. We declare a method or a variable as static when they don't conceptually belong to an object. Suppose you are building an inventory application, you will create many classes for each functionality, say stock, invoice etc. Suppose you also need many  other different operations  like finding sum, difference, printing string  etc.  Now you declare these functions as static inside a class because each of these functions do different things. Lets see an example:

class MyUtil{

   public static function printString($str){

     echo $str;

   }

  public static function getSum($a,$b){

    return $a+$b;

  }

 

}

MyUtil::printString('Hellooo');

MyUtil::getSum(3,4);

See these statements look more meaningfull, also these functions are not conceptually or logically  related in any manner.  So we just clubbed together a set of handfull functions.

Hope you understand my point.

 

   

Mo'ath Al Mallahi
by Mo'ath Al Mallahi , Senior PHP Developer , iHorizons

Hi,

You can simply define/use a static method only in case : you are'nt using an object of the same class in that method.

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.