This is similar to a previous answer, but performs some sanity checking to ensure that what you're trying to access exists, and is a valid object reference.
Save to demo.php, chmod +x demo.php && ./demo.php.
#!/usr/bin/php
<?php
class A {
public static $myvar = 'A Class';
public static $test1 = 'TEST_VALUE_1';
public static $test2 = 'TEST_VALUE_2';
}
class B {
public static $myvar = 'B Class';
}
/**
* Gets a static variable from the specified class.
* Returns FALSE if the property or class does not exist, otherwise returns the value of the property.
* @param string|object $className Can be either the class name (string) or an object (i.e., "A" or A).
* @param string $varName
* @return mixed|boolean
*/
function getClassStaticVar($className, $varName) {
if ((is_string($className) && class_exists($className) ) || is_object($className))
if (property_exists($className, $varName)) {
return $className::$$varName;
}
return FALSE; //if your property value is potentially FALSE, you might want to return another value here, like NULL.
}
function getMyVar($className) {
if (is_string($className) || is_object($className)) //is className a string or object reference?
return getClassStaticVar($className, 'myvar'); // --or-- return $className::$myvar;
return FALSE;
}
$a = getMyVar('A'); // I want 'A Class'
$b = getMyVar('B'); // I want 'B Class'
//in real code, you'd check if $a/$b === FALSE here. (see comment in getClassStaticVar() above)
echo ($a===FALSE ? 'Property/Class not found' : $a) . PHP_EOL;
echo $b . PHP_EOL;
echo getClassStaticVar("A", 'test1') . PHP_EOL;
echo getClassStaticVar(new A(), 'test2') . PHP_EOL;