Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Classes: when to use :: vs. ->?

Tags:

php

class

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?

like image 481
johnnietheblack Avatar asked Aug 03 '09 21:08

johnnietheblack


People also ask

What does :: class mean in PHP?

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.

Why :: is used in PHP?

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.

Should you use classes in PHP?

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.

What are classes used for in PHP?

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.


2 Answers

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; 
like image 91
Peter Bailey Avatar answered Sep 26 '22 00:09

Peter Bailey


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.

like image 31
Cody Caughlan Avatar answered Sep 27 '22 00:09

Cody Caughlan