what's the point of declaring static functions in PHP? what's the point of declaring static functions in PHP? php php

what's the point of declaring static functions in PHP?


Because PHP tends to be a bit loosy-goosy around strictness (?) these sort of things work. The fact that they are deprecated means that sometime in a future release, it is likely not to work anymore. So if you are calling a non-static function in a static context, your program may break in a future PHP upgrade.

As for using it right now - the advantage to declaring a function as static is that you are deciding right there how that function should be used. If you intend to use a function in a static context, you can't use $this anyway, so you are better of just being clear on what you plan to do. If you want to use the function statically, make it static. If you don't, then don't. If you want to use a function both statically and non-statically, then please recheck your requirements :P


For compatibility mode. Now calling non-static methods statically generates an E_STRICT level warning.

Why static and not instantiate the object? Each programmer will tell you a reason. I particulary preffer instantiate object than use static methods. It's clear, traceable and more reusable.

I did a test bench and the difference was minimal between instantiate and call a method than call it staticaly.

Tip: if you foresee calling methods statically defines them as well;-)


First off, you couldn't do stuff like that in your post in a strict typed language like Java. Java code doesn't compile, if you call non-static stuff in a static context. PHP is not that strict on these things (yet), but still you shouldn't do things just because you can, although it's bad practice and in some languages even 'incorrect' practice.

There sure are advantages using static methods. And it's not quite right that you gain nothing or even lose flexibility. Let's have an example:

class A {  private static $prop_a = 'property_a';  public static function b() {    echo 'called b()';    echo self::$prop_a;    $A = new A();    $A->c();  }  public function c() {    echo 'called c()';  }}

Now we can call the class this way:

A::b();

which outputs

  • called_b
  • property_a
  • called_c

But you can do the same with:

$a = new A();$a->b();$a->c();

c() is executed twice now, but you get the idea. Within your class, you can instanciate the class itself and work with it like with a regular object. But from outside, it's simply one line of code while it's 3 lines using the non-static way. Pretty cool, huh?

And as you see, you can use the static function in a non-static context, which means, you can declare your method static, but if you instanciate your class, you can simply call it like a regular method. Sounds pretty flexible to me ;)

And no, you can't use $this in a static context, but that's what self is for ;)