-1

Trying to find some information on this but am unable to get any results probably due to the chars used.

What is the difference between the following as from what I gather they do the same thing.

$classname->function()
Classname::function()

Does the second example automatically instantiate the object?

hakre
  • 193,403
  • 52
  • 435
  • 836
Shane Jones
  • 885
  • 1
  • 9
  • 27

3 Answers3

3

The former (->) is used to invoke non-static members (methods or functions / properties or variables), while the later (::) is used to invoke static members.

Non-static:

class foo{
  function bar(){ echo 'test';  }
}

$foo = new foo();
$foo->bar();

Static:

class foo{
  static function bar(){ echo 'test';  }
}

foo::bar(); // no class initialization needed

See this question for more info:

PHP: Static and non Static functions and Objects

To better understand the concept, you should check out what static methods are and how they are different from non-static.

Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • That's really cleared things up for me, I didn't know they had different names to be honest. Many thanks though. – Shane Jones Feb 07 '12 at 12:25
1

No, the second one is calling a static method. Check here.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

The second example doesn't automatically instantiate the object. So in the second way of calling, if you had used $this in the function, you will get a error like : PHP Fatal error: Using $this when not in object context.
In general, -> is used to call a non-static method, :: is used to call a static method.
But it's not so strict in php. For example:

error_reporting(E_ALL);
class A {
    public static function staticFunc() {
        echo "static";
    }

    public function instanceFunc() {
        echo "instance";    
    }
}

A::instanceFunc(); // echo "instance"
$a = new A();
$a->staticFunc();  // echo "static"

The two method called above run successfully.
Because php always implementing new features in a progressive way, to ensure compatibility, which may resulted in some detail doesn't cared much about. But if you set the error_reporting level to E_STRICT , you will find a E_STRICT error like this:
Strict Standards: Non-static method A::instanceFunc() should not be called statically

The only difference in these two ways is that: when you calling a method with :: , you can't use variable $this .

But it's still recommended you to use these two ways strict as in other Object Oriented language.
You can get more information in http://www.php-internal.com/book/?p=chapt05/05-02-class-member-variables-and-methods