I understand that there are two ways to access a PHP class - "::" and "->". Sometime one seems to work for me, while the other doesn't, and I don't understand why.
What are the benefits of each, and what is the right situation to use either?
Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.
In PHP, the double colon :: is defined as Scope Resolution Operator. It used when when we want to access constants, properties and methods defined at class level. When referring to these items outside class definition, name of class is used along with scope resolution operator.
Classes don't usually offer any benefits in terms of performance, but they very rarely have any negative effects either. Their real benefit is in making the code clearer. I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry.
Classes are a way to define new types for the language, providing a template for the data and behavior they encapsulate. Additionally, they provide functionality for creating taxonomies of types via inheritance.
Simply put, ::
is for class-level properties, and ->
is for object-level properties.
If the property belongs to the class, use ::
If the property belongs to an instance of the class, use ->
class Tester { public $foo; const BLAH; public static function bar(){} } $t = new Tester; $t->foo; Tester::bar(); Tester::BLAH;
The "::" symbol is for accessing methods / properties of an object that have been declared with the static keyword, "->" is for accessing the methods / properties of an object that represent instance methods / properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With