I am trying to access static member of a class.
my class is:
class A
{
public static $strName = 'A is my name'
public function xyz()
{
..
}
..
}
//Since I have bunch of classes stored in an array
$x = array('A');
echo $x::$strName;
I am getting error while printing. How can I print 'A is my name'
You have a syntax error with missing semicolon and because it is an array you need to access the index of 0, or else it would be trying to call class 'Array'.
Should fix it.
UPDATE
If you want to iterate over an array to call a class variable:
Not sure why you would want that, but there you go. And this has been tested, no errors were thrown, valid response of
A is my name
was received.EDIT
Apparently this only works under PHP 5.3
If
A
is a class, you can access it directly viaA::$strName
.Update:
Depending on what you have inside your array, whether its what I like to define as class objects or class literals could be a factor. I distinguish these two terms by,
If you go the class literals approach, then using a
foreach
loop with PHP5.2.8 I am given a syntax error when using the scope resolution operator.So then I thought about using the class objects approach, but the only way I could actually output the static variable was with an instance of an object and using the
self
keyword like so,And then invoke that method when iterating,
Which at that point why declare the variable
static
at all? It defeats the whole idea of accessing a variable without the need to instantiate an object.In short, once we have more information as to what you would like to do, we can then go on and provide better answers.
From inside a class and want to access a static data member of its own you can also use static:: instead of self::
I do find next one simple solution but don't know whether its good one or not.
My soln is:
If you want a working version for PHP5.2, you can use reflection to access the static property of a class.
Demo : http://ideone.com/HFJCW