3

as far as i know, :: is using for calling static functions and base class functions in a subclass. and as far as i know, usually we have to create an instance of a class for using it out of the class.

class a 
{
    public function foo()
    {
       //
    }
}

for using this class:

$instance = new a();
$instance->foo();

but its possible that we call the foo function without creating any instance and only using ::. for example the following code is written out of class and works well:

a::foo();

why does it work? and how?

Sajjad
  • 237
  • 3
  • 11
  • 2
    It's called the `Scope Resolution Operator`: http://us3.php.net/manual/en/language.oop5.paamayim-nekudotayim.php – Joseph Silber Sep 06 '11 at 04:07
  • *(related)* [What does that symbol mean in PHP](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon Sep 06 '11 at 06:57

2 Answers2

4

Calling a non-static method with the Class::method() syntax invokes the method but raises an error if it attempts to access $this. It is essentially a hold-over from the (very minimal) object-oriented programming implementation of PHP4, and it will generate a warning in PHP5; this isn't correct behaviour from an OOP standpoint, and you shouldn't rely on it.

user229044
  • 232,980
  • 40
  • 330
  • 338
2

:: is the scope resolution operator.

http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

From PHP's docs:

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

It is like ->, but has some special semantics.

David Souther
  • 8,125
  • 2
  • 36
  • 53