3

What's the difference between $foo->bar() and $foo::bar()?

animuson
  • 53,861
  • 28
  • 137
  • 147
TiGi
  • 115
  • 2
  • 9
  • 2
    Read more about static @ http://php.net/manual/en/language.oop5.static.php – Matej Baćo Feb 24 '11 at 13:58
  • 1
    possible duplicate of [In PHP, whats the difference between :: and -> ?](http://stackoverflow.com/questions/3173501/in-php-whats-the-difference-between-and) – Gordon Feb 24 '11 at 14:16
  • *(related)* [Reference: What does Symbol mean in PHP](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon Feb 24 '11 at 14:16

2 Answers2

4

$foo::bar() is a call of the static method bar(), that means the object $foo was not instanciated by the __construct() method.

When calling $foo->bar(), the object $foo has to be instanciated before! Example:

$foo = new Foo; // internally the method __constuct() is called in the Foo class!
echo $foo->bar(); 

Often you don't call a static method on a existing object like in you example ($foo), you can call it directly on the class Foo:

 Foo::bar();
powtac
  • 40,542
  • 28
  • 115
  • 170
  • What should "that means the object $foo was not instanciated by the __construct() method." mean? Its not possible to instanciate objects without calling `__construct()` :? – KingCrunch Feb 24 '11 at 14:19
  • At @KingCrunch, it is possible to instanciate a object without (auto) calling __construct(), when there is no __construct method defined. But it would not make that much sense, in such a case you would choose to call all other methods in the static way. – powtac Feb 24 '11 at 14:22
0

With the first one

$foo->bar();

you call (object) methods, whereas with

Foo::bar();

you call class (static) methods.

Its possible to call class methods on objects. That is, what your second example does. So this

$foo = new Foo;
$foo::bar();

is identical to

Foo::bar();

or even

$classname = get_class($foo);
$classname::bar();

Update: Missed something $foo can also just be a string with a classname.

$foo = 'Baz';
$foo::bar(); // Baz::bar();
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • -1: I'm very sorry to downvote, but calling static method on objects causes PHP to spit out notices, arguably meaning the code isn't entirely correct. In my humble opinion, this is a practice which many people unfortunately took up for granted. – Christian Feb 24 '11 at 14:03
  • I said its possible, not that is a good idea. Then, it was exactly, what the questioner wants to know. And it will not throw a notice anymore with PHP5.3 and up. However, I agree, thats not very good practice. (OK, maybe I forgot, that `$foo` can also be a string ^^) – KingCrunch Feb 24 '11 at 14:16