php - property_exists() to check if static property exists inside class method
one text
Solution:
Updating my code from above to include namespaces. This was the problem that was causing the method to return undefined.
The updated code is as follows:
class Generic
{
public static $propA = "A";
private static $propB = "B";
protected static $propC = "C";
public static function getProperty(string $property): string
{
if (!property_exists('JLDN\Generic', $property)) :
return "Undefined Property";
endif;
return self::$$property;
}
}
foreach (['propA', 'propB', 'propC', 'nonProperty'] as $prop) :
printf("<p>Property: %s::%s - %s</p>\n", 'Generic', $prop, print_r(Generic::getProperty($prop), true));
endforeach;
Output:
Property: Generic::propA - A
Property: Generic::propB - B
Property: Generic::propC - C
Property: Generic::nonProp - Undefined Property
Source