Search code examples
phpstaticconstantsdefined

PHP defined method returns false value but static variable exists


Can someone explain this to me?

<?php 
class SomeClass {
  public static $SomeStatic = "SomeValue";
}

$class_name = "SomeClass";

var_dump("{$class_name}::\$SomeStatic"); // shows "SomeClass::$SomeStatic"

var_dump($class_name::$SomeStatic); // shows "SomeValue"

var_dump(defined("{$class_name}::\$SomeStatic")); // shows "bool(false)"

Why does defined method returns false? To think that the 2nd var_dump returns a value.


Solution

  • A static variable isn't a constant, so defined returns false.

    To check if a class has a static property, you can use this function:

    function has_static_property($class, $property_name)
    {
        $reflection        = new ReflectionClass($class);
        $static_properties = $reflection->getStaticProperties();
    
        return array_key_exists($property_name, $static_properties);
    }
    

    More information about the ReflectionClass class and the getStaticProperties method can be found on the PHP documentation.