Static methods in PHP

donRumatta picture donRumatta · Feb 9, 2012 · Viewed 71.7k times · Source

Why in PHP you can access static method via instance of some class but not only via type name?

UPDATE: I'm .net developer but i work with php developers too. Recently i've found this moment about static methods called from instance and can't understand why it can be usefull.

EXAMPLE:

class Foo
{
    public static Bar()
    {
    }
}

We can accept method like this:

var $foo = new Foo();
$foo.Bar(); // ??????

Answer

Ibrahim Azhar Armar picture Ibrahim Azhar Armar · Feb 9, 2012

In PHP

the class is instantiated using the new keyword for example;

$MyClass = new MyClass();

and the static method or properties can be accessed by using either scope resolution operator or object reference operator. For example, if the class MyClass contains the static method Foo() then you can access it by either way.

$MyClass->Foo();

Or

MyClass::Foo()

The only rule is that static methods or properties are out of object context. For example, you cannot use $this inside of a static method.