ReflectionClass::getDefaultProperties

(PHP 5)

ReflectionClass::getDefaultPropertiesВозвращает свойства по умолчанию

Описание

public array ReflectionClass::getDefaultProperties ( void )

Возвращает свойства класса по умолчанию (включая наследованные свойства).

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Ассоциативный массив (array) свойств по умолчанию, ключами которого являются имена свойств, а значениями -- соответствующие значения по умолчанию или же NULL, если этому свойству не было задано значение по умолчанию. Функция не различает static (статические) и non static (не статические) свойства, а также не предоставляет информацию о модификаторах видимости при выводе.

Примеры

Пример #1 Пример использования ReflectionClass::getDefaultProperties()

<?php
class Bar {
    protected 
$inheritedProperty 'наследованное свойство по умолчанию';
}

class 
Foo extends Bar {
    public 
$property 'свойство по умолчанию';
    private 
$privateProperty 'закрытое свойство по умолчанию';
    public static 
$staticProperty 'статическое свойство';
    public 
$defaultlessProperty;
}

$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

Результат выполнения данного примера:

array(5) {
   ["staticProperty"]=>
   string(14) "статическое свойство"
   ["property"]=>
   string(15) "свойство по умолчанию"
   ["privateProperty"]=>
   string(22) "закрытое свойство по умолчанию"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "наследованное свойство по умолчанию"
}

Смотрите также

Коментарии

This will return all properties in a class and any parent classes.  The array will have keys set to the property names and empty values.
2010-01-20 17:20:17
http://php5.kiev.ua/manual/ru/reflectionclass.getdefaultproperties.html
Worth noting that it will not return private parameters of parent class...
so it works exactly as get_class_vars or get_object_vars
2011-08-04 04:02:30
http://php5.kiev.ua/manual/ru/reflectionclass.getdefaultproperties.html
runaurufu is not quite right, get_class_vars() does not return protected params, while this one does.

Thus it's extremely useful when having an abstract parent class and protected properties overriding in children.
For example, I use a class factory and one of the children has some static test methods that still need to output a paramether name, like $this->name, etc. With this example code, one can use static::getNotStaticProperty('name'), but not get_class_vars('name').

Try it:

trait static_reflector {
    /*
     * a purely static function that returns default properties of the non-static instance of the same class
     */
    static protected function getNonStaticProperty($key) {
        $me = get_class();
        $reflectionClass = new \ReflectionClass($me);
        $properties_list = $reflectionClass->getDefaultProperties();
        if (isset($properties_list[$key]))
            return $var_name = $properties_list[$key];
        else throw new RuntimeException("BUG: Unable to reflect non-static property '{$key}' from default properties of class {$me}");
    }
}

class a {

    use \static_reflector;

    protected $key_a = 'test ok';

    public static function test() {
        echo static::getNonStaticProperty('key_a')."\n";

        try {
            print static::getNonStaticProperty('key_b');
            echo "FAIL No exception thrown";
        } catch (RuntimeException $e) {
            echo "OK ".$e->getMessage();
        }

    }
}

echo get_class_vars('a')['key_a']; 
a::test();

this will return:
Notice: Undefined index: key_a in ...
test ok
OK BUG: Unable to reflect non-static property 'key_b' from default properties of class a

ps: Yes, this is copied from a unit test.
2016-03-17 02:15:18
http://php5.kiev.ua/manual/ru/reflectionclass.getdefaultproperties.html

    Поддержать сайт на родительском проекте КГБ