Getting static property from a class with dynamic class name in PHP

后端 未结 11 500
情歌与酒
情歌与酒 2020-11-30 01:44

I have this:

  • one string variable which holds the class name ($classname)
  • one string variable with holds the property name ($propert
11条回答
  •  一生所求
    2020-11-30 02:06

    Getting and setting both static and non static properties without using Reflection

    Using Reflection works but it is costly

    Here is what I use for this purpose,

    It works for PHP 5 >= 5.1.0 because I'm using property_exist

    function getObjectProperty($object, $property)
    {
        if (property_exists(get_class($object), $property)) {
            return array_key_exists($property, get_object_vars($object))
                ? $object->{$property}
                : $object::$$property;
        }
    }
    
    function setObjectProperty($object, $property, $value)
    {
        if (property_exists(get_class($object), $property)) {
            array_key_exists($property, get_object_vars($object))
                ? $object->{$property} = $value
                : $object::$$property = $value;
        }
    }
    

提交回复
热议问题