3

Possible Duplicate:
where we use object operator “->” in php

In PHP 5, what are the advantages of typing $class::method() instead of $class->method()?

As in any performance or functional differences. Or is this just a way of forcing code non-PHP4 friendly because of the complete rewrite?

Community
  • 1
  • 1
tim
  • 2,530
  • 3
  • 26
  • 45

2 Answers2

11

In PHP5, the two aren't interchangeable.

Static method calls will perform faster than non-static calls (over many iterations) but then the method is called in the static context and there is no object available to the called method.

The only reason PHP lets you call a non-static method using the static notation was for backwards compatibility in PHP 4 (because PHP 4 didn't have the static modifier for functions, or public/protected/private). If you do call a non-static method statically, you get a warning about "Strict Standards" output, and eventually this may fail with a fatal error.

So the answer really is to call the method the way it was supposed to be called. If it is a static method in PHP 5, then call it statically Class::method(), if it is a public method, then call it using the object $class->method().

Consider this code (run in PHP 5):

class Foo {
    protected $bar = 'bar';

    function f() {
        echo $this->bar;
    }
}

echo Foo::f(); // Fatal error: Using $this when not in object context
drew010
  • 68,777
  • 11
  • 134
  • 162
  • vote up =great; comment that you did it = silly; comment on that (me) =?? –  Aug 06 '12 at 21:46
  • @tim Let me know if this addressed your question properly or if there is something else you are wondering about. – drew010 Aug 06 '12 at 22:05
0

$class::method() calls a static method of the class whereas $class->method() calls a public standard method of the class.

Naftali
  • 144,921
  • 39
  • 244
  • 303