Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between :: and -> in PHP

Tags:

scope

php

static

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?

like image 769
sdkfasldf Avatar asked May 10 '10 17:05

sdkfasldf


People also ask

What is the difference between :: and -> in PHP?

They are for different function types. -> is always used on an object for static and non-static methods (though I don't think it's good practice use -> for static methods). :: is only used for static methods and can be used on objects (as of PHP 5.3) and more importantly classes.

What is -> mean in PHP?

The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator.

What is the difference between double colon and arrow in PHP?

The arrow means the addChild is called as a member of the object (in this case $sxe). The double colon means that addChild is a member of the SimpleXMLElement class.

What is the difference between == and === in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.


1 Answers

The double colon is used when you don't instantiate a class

class StaticDemo {...};
StaticDemo::static

if you do instantiate, use -->

class StaticDemo {...};
$s = new StaticDemo();
$s->static;

This is explained further at http://php.net/manual/en/language.oop5.patterns.php

like image 53
Adam Hopkinson Avatar answered Oct 04 '22 02:10

Adam Hopkinson