Although it is allowed to access class variables using the syntax:- $object::$variable, does it hold any significance i.e. in case of accessing class variables we can use either the classname or an object of that class to access a class variable isn't it?
Asked
Active
Viewed 609 times
-4
-
FYI this operator is called `T_PAAMAYIM_NEKUDOTAYIM` as [seen in the docs](http://php.net/manual/en/tokens.php), not a "scope resolution operator", since it has little to do with scope in PHP. – NDM Sep 10 '13 at 12:31
-
1@War10ck "Static classes" do not exist in PHP ([see here](http://stackoverflow.com/questions/468642/is-it-possible-to-create-static-classes-in-php-like-in-c)). – ComFreek Sep 10 '13 at 12:36
-
ooh, apparently it *is* called a "scope resolution operator" after all :) – NDM Sep 10 '13 at 12:39
2 Answers
0
This operator is used to access static variables. This means that the variable is linked to the class, and not to an instance of that class. i.e. shared over all instances.
here's an example to show you what I mean:
class MyClass
{
public static $myStaticVar;
public $myObjectVar;
}
$instance1 = new MyClass();
$instance2 = new MyClass();
// normal vars are linked to an instance of a class
$instance1->myObjectVar = 'value1';
$instance2->myObjectVar = 'value2';
// statics are shared between all instances of the same class
$instance1::$myStaticVar = 'value3';
echo $instance2::$myStaticVar; // results in 'value3'!

NDM
- 6,731
- 3
- 39
- 52
-1
Do you mean this?
<?php
class A {
public static $b = 'Hello World!';
}
echo A::$b;
$obj = new A();
echo $obj::$b;
Warning: I do not recommend to access a static class member using an instance variable.
This only works for PHP >= 5.3.0.
PHP <= 5.2.17 doesn't like $obj::$b
and throws a syntax error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ';'

ComFreek
- 29,044
- 18
- 104
- 156
-
Bubba downvoted all other answers to make his come up on top, I checked his profile to confirm this. – NDM Sep 10 '13 at 13:59
-
@NDM Thanks for informing me. Have you already reported him? (I can't see his downvotes at his profile, can you give me a link, please?) – ComFreek Sep 10 '13 at 14:03
-
http://stackoverflow.com/users/660636/bubba?tab=reputation the -2 on this question marks 2 downvotes, yours and my answer... I've just downvoted him aswell, dont think flagging will help... – NDM Sep 10 '13 at 14:06
-
@NDM Please revert your downvote ('revenge' doesn't help). Flagging defintely helps, the SO moderator team is very kind. – ComFreek Sep 10 '13 at 14:14