ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

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
تم إضافة السؤال من قبل Rashid Anwar , senior php developer , sparx it solution pvt ltd.
تاريخ النشر: 2013/09/22
Imranullah Khan
من قبل 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
من قبل islam khalil , Technical Manager , iCloudit

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

Nouphal Muhammed
من قبل 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
من قبل 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.

المزيد من الأسئلة المماثلة