Reputation: 1014
Given a class:
class SomeClass{
static $information = 'useful information';
}
I a trying to access a static variable in a set of php classes. Each class has the $information static variable. If I access the static variable directly
echo SomeClass::$information;
The program outputs the information, however if I try to access it storing it in a variable I get a error that the '::' is unexpected.
$class = SomeClass;
echo $class::$information;
The reason for storing the class in a variable is so that I can have a function that can create an array of Users or an array of Projects for example.
Upvotes: 1
Views: 1110
Reputation: 3847
class SomeClass {
public static $information = 'useful information';
public static function getInformation() {
return self::$information;
}
}
Then you can do the following:
# Static Access
echo SomeClass::$information;
echo SomeClass::getInformation();
# Static Access via Class Name in Variable
$someClass = 'SomeClass';
echo $someClass::$information;
## Instantiated access
$someClass = new SomeClass();
echo $someClass->$information;
echo $someClass->getInformation();
Upvotes: 1
Reputation: 1039
You can do this:
$class = SomeClass::class;
echo $class::$information;
::class
gets the fully qualified name of a class as a string.
Upvotes: 1
Reputation: 659
You can't store a reference to class in a variable, it is useless.
Instead you can store the class name in a variable and call the static method or variable:
$class = 'SomeClass';
echo $class::$information;
Upvotes: 0