Alex Rivera | Logout

Difference between :: and -> in PHP

Asked 2010-05-10T17:13:53.747
15

I always see people in serious projects use :: everywhere, and -> only occasionally in local environment.

I only use -> myself and never end up in situations when I need a static value outside of a class. Am I a bad person?

As I understand, the only situation when -> won't work is when I try following:

class StaticDemo {  
    private static $static  
}

$staticDemo = new StaticDemo( );

$staticDemo->static; // wrong  
$staticDemo::static; // right

But am I missing out on some programming correctness when I don't call simple public methods by :: ?

Or is it just so that I can call a method without creating an instance?

Edit
Report

3 Answers

3

-> is for an instanciated class. :: is a static call.

:: is used in inheritance constructors (a child accessing a parent constructor) and when referring to a static method inside another method.

I wouldn't say not using static calls makes you a bad person either!

answered 2010-05-10T17:17:56.563
1

Use "->" when in object context and "::" when accessing the class directly. In your example that would be:

class StaticDemo {
    public static $staticVar = 'blabla';
    public $normalVar = 'foobar';
}

$foo = new StaticDemo();
echo $foo->normalVar; //object context, echoes "foobar"
echo StaticDemo::staticVar; //class or "static" context, echoes "blabla"

Read this for detailed intel.

answered 2010-05-10T17:20:43.347
1

As others have said,

  • :: 'double colon' is for referencing a static property or method.
  • -> 'dash arrow' is for referencing a property or method of a class instance.

But also its worth noting that

  • :: is often used in texts as shorthand to refer to a property or method that belongs to a certain class (whether it's static or instance).

See the 'Note...in documentation...' : http://books.google.co.uk/books?id=qVLjFk_4zVYC&lpg=PA66&dq=php%205%20objects&pg=PA46#v=onepage&q=php%205%20objects&f=false

answered 2010-05-10T18:44:36.907

Your Answer