PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Подсказване на тип> <Сравняване на обекти
Last updated: Fri, 28 Nov 2008

view this page in

Отражение

Въведение

PHP 5 разполага с цялостен API интерфейс за работа с отражения, което добавя възможността за обратно инженерство (reverse engineering) на класове, интерфейси, функции и методи, както и разширения. Освен това API-интерфейсът за отражения предлага начини за извличане на документиращи коментари за функции, класове и методи.

API-интерфейсът за отражения е обектно-ориентирано разширение на Zend Engine, което се състои от следните класове:

<?php
class Reflection { }
interface 
Reflector { }
class 
ReflectionException extends Exception { }
class 
ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { }
class 
ReflectionParameter implements Reflector { }
class 
ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { }
class 
ReflectionClass implements Reflector { }
class 
ReflectionObject extends ReflectionClass { }
class 
ReflectionProperty implements Reflector { }
class 
ReflectionExtension implements Reflector { }
?>

Забележка: За повече информация относно тези класове, вижте следващите глави.

Нека разгледаме следния пример:

Example #1 Проста употреба на API интерфейса за отражения

<?php
Reflection
::export(new ReflectionClass('Exception'));
?>

Примерът по-горе ще изведе:

Class [ <internal> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [6] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
  }

  - Methods [9] {
    Method [ <internal> final private method __clone ] {
    }

    Method [ <internal, ctor> public method __construct ] {

      - Parameters [2] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
      }
    }

    Method [ <internal> final public method getMessage ] {
    }

    Method [ <internal> final public method getCode ] {
    }

    Method [ <internal> final public method getFile ] {
    }

    Method [ <internal> final public method getLine ] {
    }

    Method [ <internal> final public method getTrace ] {
    }

    Method [ <internal> final public method getTraceAsString ] {
    }

    Method [ <internal> public method __toString ] {
    }
  }
}

Reflector

Reflector е интерфейс, реализиран от всички класове от тип Reflection, които могат да бъдат експортирани.

<?php
interface Reflector
{
    public 
string __toString()
    public static 
string export()
}
?>

ReflectionException

ReflectionException наследява стандартното изключение Exception и се хвърля от API-интерфейса за отражения. Няма специфични методи и свойства.

ReflectionFunction

Класът ReflectionFunction позволява извличане на информация за функции.

<?php
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector
{
    final private 
__clone()
    public 
void __construct(string name)
    public 
string __toString()
    public static 
string export()
    public 
string getName()
    public 
bool isInternal()
    public 
bool isDisabled()
    public 
mixed getClosure() /* От PHP 5.3.0 */
    
public bool isUserDefined()
    public 
string getFileName()
    public 
int getStartLine()
    public 
int getEndLine()
    public 
string getDocComment()
    public array 
getStaticVariables()
    public 
mixed invoke([mixed args [, ...]])
    public 
mixed invokeArgs(array args)
    public 
bool returnsReference()
    public 
ReflectionParameter[] getParameters()
    public 
int getNumberOfParameters()
    public 
int getNumberOfRequiredParameters()
}
?>

Родителският клас ReflectionFunctionAbstract има същите методи с изключение на invoke(), invokeArgs(), export() и isDisabled().

Забележка: getNumberOfParameters() и getNumberOfRequiredParameters() бяха добавени в PHP 5.0.3, а invokeArgs() беше добавен в PHP 5.1.0.

За да извършите интроспекция на функция, първо трябва да направите инстанция на класа ReflectionFunction. След това може да извикате който и да е от горните методи на тази инстанция.

Example #2 Употреба на класа ReflectionFunction

<?php
/**
 * Обикновен брояч
 *
 * @return    int
 */
function counter()
{
    static 
$c 0;
    return 
$c++;
}

// Създаване на инстанция на класа ReflectionFunction
$func = new ReflectionFunction('counter');

// Извеждане на основна информация
printf(
    
"===> %s функция '%s'\n".
    
"     декларирана в %s\n".
    
"     на редове от %d до %d\n",
    
$func->isInternal() ? 'Вътрешна' 'Дефинирана от потребителя',
    
$func->getName(),
    
$func->getFileName(),
    
$func->getStartLine(),
    
$func->getEndline()
);

// Извеждане на документиращ коментар
printf("---> Документация:\n %s\n"var_export($func->getDocComment(), 1));

// Извеждане на статичните променливи, ако има такива
if ($statics $func->getStaticVariables())
{
    
printf("---> Статични променливи: %s\n"var_export($statics1));
}

// Извикване на функция
printf("---> Резултат от извикването: ");
var_dump($func->invoke());


// може да се използва метода export()
echo "\nReflectionFunction::export() резултат:\n";
echo 
ReflectionFunction::export('counter');
?>

Забележка: Методът invoke() приема произволен брой аргументи, които се предават към функцията точно както при call_user_func().

ReflectionParameter

Класът ReflectionParameter позволява извличане на информация за параметрите на функции и методи.

<?php
class ReflectionParameter implements Reflector
{
    final private 
__clone()
    public 
void __construct(string function, string parameter)
    public 
string __toString()
    public static 
string export()
    public 
string getName()
    public 
bool isPassedByReference()
    public 
ReflectionClass getDeclaringClass()
    public 
ReflectionClass getClass()
    public 
bool isArray()
    public 
bool allowsNull()
    public 
bool isPassedByReference()
    public 
bool isOptional()
    public 
bool isDefaultValueAvailable()
    public 
mixed getDefaultValue()
    public 
int getPosition()
}
?>

Забележка: getDefaultValue(), isDefaultValueAvailable() и isOptional() бяха добавени в PHP 5.0.3, a isArray() беше добавен в PHP 5.1.0. getDeclaringFunction() и getPosition() бяха добавени в PHP 5.2.3.

За да извършите интроспекция на параметрите на функция, първо трябва да направите инстанция на класовете ReflectionFunction или ReflectionMethod и да използвате техните методи getParameters(), за да върнете масива от параметри.

Example #3 Употреба на класа ReflectionParameter

<?php
function foo($a$b$c) { }
function 
bar(Exception $a, &$b$c) { }
function 
baz(ReflectionFunction $a$b 1$c null) { }
function 
abc() { }

// Създаване на инстанция на ReflectionFunction
// с параметри от командния ред
$reflect = new ReflectionFunction($argv[1]);

echo 
$reflect;

foreach (
$reflect->getParameters() as $i => $param) {
    
printf(
        
"-- Параметър #%d: %s {\n".
        
"   Клас: %s\n".
        
"   Позволява NULL: %s\n".
        
"   Предаден по адрес: %s\n".
        
"   Опционален?: %s\n".
        
"}\n",
        
$i// $param->getPosition() може да се използва от PHP 5.2.3
        
$param->getName(),
        
var_export($param->getClass(), 1),
        
var_export($param->allowsNull(), 1),
        
var_export($param->isPassedByReference(), 1),
        
$param->isOptional() ? 'да' 'не'
    
);
}
?>

ReflectionClass

Класът ReflectionClass позволява извличане на информация за класове и интерфейси.

<?php
class ReflectionClass implements Reflector
{
    final private 
__clone()
    public 
void __construct(string name)
    public 
string __toString()
    public static 
string export(mixed class, bool return)
    public 
string getName()
    public 
bool isInternal()
    public 
bool isUserDefined()
    public 
bool isInstantiable()
    public 
bool hasConstant(string name)
    public 
bool hasMethod(string name)
    public 
bool hasProperty(string name)
    public 
string getFileName()
    public 
int getStartLine()
    public 
int getEndLine()
    public 
string getDocComment()
    public 
ReflectionMethod getConstructor()
    public 
ReflectionMethod getMethod(string name)
    public 
ReflectionMethod[] getMethods()
    public 
ReflectionProperty getProperty(string name)
    public 
ReflectionProperty[] getProperties()
    public array 
getConstants()
    public 
mixed getConstant(string name)
    public 
ReflectionClass[] getInterfaces()
    public 
bool isInterface()
    public 
bool isAbstract()
    public 
bool isFinal()
    public 
int getModifiers()
    public 
bool isInstance(stdclass object)
    public 
stdclass newInstance(mixed args)
    public 
stdclass newInstanceArgs(array args)
    public 
ReflectionClass getParentClass()
    public 
bool isSubclassOf(ReflectionClass class)
    public array 
getStaticProperties()
    public 
mixed getStaticPropertyValue(string name [, mixed default])
    public 
void setStaticPropertyValue(string namemixed value)
    public array 
getDefaultProperties()
    public 
bool isIterateable()
    public 
bool implementsInterface(string name)
    public 
ReflectionExtension getExtension()
    public 
string getExtensionName()
}
?>

Забележка: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() и setStaticPropertyValue() бяха добавени в PHP 5.1.0, а newInstanceArgs() беше добавен в PHP 5.1.3.

За да извършите интроспекция на клас, първо трябва да направите инстанция на ReflectionClass. След това може да извикате който и да е от горните методи на тази инстанция.

Example #4 Употреба на класа ReflectionClass

<?php
interface Serializable
{
    
// ...
}

class 
Object
{
    
// ...
}

/**
 * Клас Counter
 */
class Counter extends Object implements Serializable
{
    const 
START 0;
    private static 
$c Counter::START;

    
/**
     * Извикване на брояча
     *
     * @access  public
     * @return  int
     */
    
public function count() {
        return 
self::$c++;
    }
}

// Създаване на инстанция на класа ReflectionClass
$class = new ReflectionClass('Counter');

// Извеждане на основна информация
printf(
    
"===> %s%s%s %s '%s' [наследява %s]\n" .
    
"     деклариран в %s\n" .
    
"     на редове от %d да %d\n" .
    
"     притежава модификатори %d [%s]\n",
        
$class->isInternal() ? 'Вътрешен' 'Дефиниран от потребителя',
        
$class->isAbstract() ? ' абстрактен' '',
        
$class->isFinal() ? ' финален' '',
        
$class->isInterface() ? ' интерфейс' ' клас',
        
$class->getName(),
        
var_export($class->getParentClass(), 1),
        
$class->getFileName(),
        
$class->getStartLine(),
        
$class->getEndline(),
        
$class->getModifiers(),
        
implode(' 'Reflection::getModifierNames($class->getModifiers()))
);

// Извеждане на документиращ коментар
printf("---> Документация:\n %s\n"var_export($class->getDocComment(), 1));

// Извежда интерфейсите реализирани от този клас
printf("---> Реализира:\n %s\n"var_export($class->getInterfaces(), 1));

// Извежда константите на класа
printf("---> Константи: %s\n"var_export($class->getConstants(), 1));

// Извежда свойствата на класа
printf("---> Свойства: %s\n"var_export($class->getProperties(), 1));

// Извежда методите на класа
printf("---> Методи: %s\n"var_export($class->getMethods(), 1));

// Ако класът може да се инстранциира, създава инстранция
if ($class->isInstantiable()) {
    
$counter $class->newInstance();

    echo 
'---> $counter е инстанция? ';
    echo 
$class->isInstance($counter) ? 'да' 'не';

    echo 
"\n---> new Object() е инстанция? ";
    echo 
$class->isInstance(new Object()) ? 'да' 'не';
}
?>

Забележка: Методът newInstance() приема произволен брой аргументи, които се предават към функцията точно както при call_user_func().

Забележка: $class = new ReflectionClass('Foo'); $class->isInstance($arg) е еквивалентно на $arg instanceof Foo или is_a($arg, 'Foo').

ReflectionObject

Класът ReflectionObject позволява извършването на обратно инженерство върху обекти.

<?php
class ReflectionObject extends ReflectionClass
{
    final private 
__clone()
    public 
void __construct(mixed object)
    public 
string __toString()
    public static 
string export(mixed objectbool return)
}
?>

ReflectionMethod

Класът ReflectionMethod позволява извличане на информация за методи.

<?php
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector
{
    public 
void __construct(mixed class, string name)
    public 
string __toString()
    public static 
string export(mixed class, string namebool return)
    public 
mixed invoke(stdclass object [, mixed args [, ...]])
    public 
mixed invokeArgs(stdclass object, array args)
    public 
bool isFinal()
    public 
bool isAbstract()
    public 
bool isPublic()
    public 
bool isPrivate()
    public 
bool isProtected()
    public 
bool isStatic()
    public 
bool isConstructor()
    public 
bool isDestructor()
    public 
int getModifiers()
    public 
mixed getClosure() /* От PHP 5.3.0 */
    
public ReflectionClass getDeclaringClass()

    
// Наследени от ReflectionFunctionAbstract
    
final private __clone()
    public 
string getName()
    public 
bool isInternal()
    public 
bool isUserDefined()
    public 
string getFileName()
    public 
int getStartLine()
    public 
int getEndLine()
    public 
string getDocComment()
    public array 
getStaticVariables()
    public 
bool returnsReference()
    public 
ReflectionParameter[] getParameters()
    public 
int getNumberOfParameters()
    public 
int getNumberOfRequiredParameters()
}
?>

За да извършите интроспекция на метод, първо трябва да направите инстанция на ReflectionMethod. След това може да извикате който и да е от горните методи на тази инстанция.

Example #5 Употреба на класа ReflectionMethod

<?php
class Counter
{
    private static 
$c 0;

    
/**
     * Увеличава брояча
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    
final public static function increment()
    {
        return ++
self::$c;
    }
}

// Създаване на инстанция на класа ReflectionMethod
$method = new ReflectionMethod('Counter''increment');

// Извеждане на основна информация
printf(
    
"===> %s%s%s%s%s%s%s метод '%s' (който е %s)\n" .
    
"     деклариран в %s\n" .
    
"     на редове от %d до %d\n" .
    
"     притежава модификатори %d[%s]\n",
        
$method->isInternal() ? 'Вътрешен' 'Дефиниран от потребителя',
        
$method->isAbstract() ? ' абстрактен' '',
        
$method->isFinal() ? ' финален' '',
        
$method->isPublic() ? ' public' '',
        
$method->isPrivate() ? ' private' '',
        
$method->isProtected() ? ' protected' '',
        
$method->isStatic() ? ' статичен' '',
        
$method->getName(),
        
$method->isConstructor() ? 'конструктор' 'нормален метод',
        
$method->getFileName(),
        
$method->getStartLine(),
        
$method->getEndline(),
        
$method->getModifiers(),
        
implode(' 'Reflection::getModifierNames($method->getModifiers()))
);

// Извеждане на документиращ коментар
printf("---> Документация:\n %s\n"var_export($method->getDocComment(), 1));

// Извежда статичните променливи ако съществуват
if ($statics$method->getStaticVariables()) {
    
printf("---> Статични променливи: %s\n"var_export($statics1));
}

// Извиква метода
printf("---> Резултат от извикването: ");
var_dump($method->invoke(NULL));
?>

Example #6 Getting closure using ReflectionMethod class

<?php

class Example {
    static function 
printer () {
        echo 
"Hello World!\n";
    }
}

$class = new ReflectionClass('Example');
$method $class->getMethod('printer');
$closure $method->getClosure(); /* От PHP 5.3.0 */
$closure(); // Hello World!

?>

Забележка: Опитът да се извика private, protected или абстрактен метод ще доведе до генериране на изключение от метода invoke().

Забележка: Както се вижда от примера по-горе, при статични методи, трябва да се предава NULL като първи аргумент на invoke(). При нестатични методи, се предава инстанцията на класа.

ReflectionProperty

Класът ReflectionProperty позволява извличане на информация за свойства.

<?php
class ReflectionProperty implements Reflector
{
    final private 
__clone()
    public 
void __construct(mixed class, string name)
    public 
string __toString()
    public static 
string export(mixed class, string namebool return)
    public 
string getName()
    public 
bool isPublic()
    public 
bool isPrivate()
    public 
bool isProtected()
    public 
bool isStatic()
    public 
bool isDefault()
    public 
void setAccessible() /* От PHP 5.3.0 */
    
public int getModifiers()
    public 
mixed getValue(stdclass object)
    public 
void setValue(stdclass objectmixed value)
    public 
ReflectionClass getDeclaringClass()
    public 
string getDocComment()
}
?>

Забележка: getDocComment() беше добавен в PHP 5.1.0. setAccessible() беше добавен в PHP 5.3.0.

За да извършите интроспекция на свойство, първо трябва да направите инстанция на ReflectionProperty. След това може да извикате който и да е от горните методи на тази инстанция.

Example #7 Употреба на класа ReflectionProperty

<?php
class String
{
    public 
$length  5;
}

// Създаване на инстанция на класа ReflectionProperty
$prop = new ReflectionProperty('String''length');

// Извеждане на основна информация
printf(
    
"===> %s%s%s%s свойството '%s' (което беше %s)\n" .
    
"     притежава модификатори %s\n",
        
$prop->isPublic() ? ' public' '',
        
$prop->isPrivate() ? ' private' '',
        
$prop->isProtected() ? ' protected' '',
        
$prop->isStatic() ? ' статичен' '',
        
$prop->getName(),
        
$prop->isDefault() ? 'декларирано по време на компилация' 'създадено по време на стартиране',
        
var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Създаване на инстанция на String
$obj= new String();

// Връщане на текущата стойност
printf("---> Стойността е: ");
var_dump($prop->getValue($obj));

// Променяне на стойността
$prop->setValue($obj10);
printf("---> Установяване а стойността в 10, новата стойност е: ");
var_dump($prop->getValue($obj));

// Dump на обекта
var_dump($obj);
?>

Забележка: Опитът да се вземе или установи стойнстта на private или protected свойсво на клас ще предизвика генериране на изключение.

ReflectionExtension

Класът ReflectionExtension позволява извличане на информация за разширения. Можете да извлечете всички заредени разширения по време на изпълнение чрез get_loaded_extensions().

<?php
class ReflectionExtension implements Reflector {
    final private 
__clone()
    public 
void __construct(string name)
    public 
string __toString()
    public static 
string export(string namebool return)
    public 
string getName()
    public 
string getVersion()
    public 
ReflectionFunction[] getFunctions()
    public array 
getConstants()
    public array 
getINIEntries()
    public 
ReflectionClass[] getClasses()
    public array 
getClassNames()
    public 
string info()
}
?>

За да извършите интроспекция на разширение, първо трябва да направите инстанция на ReflectionExtension. След това може да извикате който и да е от горните методи на тази инстанция.

Example #8 Употреба на класа ReflectionExtension

<?php
// Създаване на инстанция на класа ReflectionExtension
$ext = new ReflectionExtension('standard');

// Извеждане на основна информация
printf(
    
"Наименование  : %s\n" .
    
"Версия        : %s\n" .
    
"Функции       : [%d] %s\n" .
    
"Константи     : [%d] %s\n" .
    
"INI стойности : [%d] %s\n" .
    
"Класове       : [%d] %s\n",
        
$ext->getName(),
        
$ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
        
sizeof($ext->getFunctions()),
        
var_export($ext->getFunctions(), 1),

        
sizeof($ext->getConstants()),
        
var_export($ext->getConstants(), 1),

        
sizeof($ext->getINIEntries()),
        
var_export($ext->getINIEntries(), 1),

        
sizeof($ext->getClassNames()),
        
var_export($ext->getClassNames(), 1)
);
?>

Наследяване на класовете за отражение

В случай че искате да създадете специализирани версии на вградените класове (примерно за да оцветите кода HTML при експортиране посредством лесни за достъп свойства вместо чрез методи или чрез прилагането на методи от тип utility), можете спокойно да ги наследите.

Example #9 Наследяване на вградени класове

<?php
/**
 * Клас My_Reflection_Method
 */
class My_Reflection_Method extends ReflectionMethod
{
    public 
$visibility = array();

    public function 
__construct($o$m)
    {
        
parent::__construct($o$m);
        
$this->visibilityReflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Демонстрационен клас #1
 *
 */
class {
    protected function 
x() {}
}

/**
 * Демонстрационен клас #2
 *
 */
class extends {
    function 
x() {}
}

// Извеждане на информацията
var_dump(new My_Reflection_Method('U''x'));
?>

Забележка: Внимание: Ако предефинирате конструктор, не забравяйте да извикате конструктора на родителския клас преди всякакъв друг код. В противен случай резултатът ще е следния: Fatal error: Internal error: Failed to retrieve the reflection object



add a note add a note User Contributed Notes
Отражение
gromit at mailinator dot com
29-Jul-2008 11:37
Be aware that calling the method newInstanceArgs with an empty array will still call the constructor with no arguments. If the class has no constructor then it will generate an exception.

You need to check if a constructor exists before calling this method or use try and catch to act on the exception.
meecrob at k42b3 dot com
20-Jun-2008 01:47
When your class extends a parent class you maybe want the name
of them. Using getParentClass() is maybe a bit confusing. When
you want the name as string try the following.

<?php
$class
= new ReflectionClass('whatever');

$parent = (array) $class->getParentClass();

if(
array_key_exists('name', $parent))
{
   
# name of the parent class
   
$parent = parent['name'];
}
else
{
   
# no parent class avaible
   
$parent = false;
}
?>

When you turn getParentClass() to an array it will result either
array(0 => false) when no parent class exist or
array('name' => 'name of the parent class'). Tested on PHP 5.2.4
fgm at riff dot org
11-May-2008 10:44
The note about the signature of the ReflectionParameter constructor is actually incomplete, at least in 5.2.5: it is possible to use an integer for the second parameter, and the constructor will use it to return the n-th parameter.

This allows you to obtain proper ReflectionParameter objects even when documenting code from extensions which (strangely enough) define several parameters with the same name. The string-based constructor always returns the first parameter with the matching name, whereas the integer-based constructor correctly returns the n-th parameter.

So, in short, this works:
<?php
// supposing the extension defined something like:
// Some_Class::someMethod($a, $x, $y, $x, $y)
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 4);
// returns the last parameter, whereas
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 'y');
// always returns the first $y at position 2
?>
Niels Jaeckel
09-Apr-2008 12:32
I think there are still some limitations in the reflection abilities:

* ReflectionClass :: getConstants() returns an associative array with the constants and their values inside. I don't understand, why they don't use an object there, too (e.g. ReflectionConstant). The final effect is, that you aren't able to read out the DocComment of constants.

* There is no nice way to access the default values of properties. You can workaround a bit with get_class_vars(), but this just returns the values of public properties. No way to access protected or even private properties.

* PHP 5 has a nice feature called type hinting. This is completely omitted. You may ask, if a certain parameter is an array, but you won't get the denoted type hint.

Maybe this is, or will be extended. I hope so.

hth,
Niels
rob at endertech dot com
08-Apr-2008 01:34
PHP 5.3 will receive Java's setAccessible() functionality for accessing protected/privates.
Andrea Giammarchi
17-Feb-2008 04:41
I encountered a weird problem with ReflectionFunction, described in ticket 44139 of PHP Bugs.

If for some reason you need to call with invoke, or invokeArgs, a function like array_unshift (that accepts internally the array by reference) you could use this code to avoid the generated warning or fatal error.

<?php
function unshift(){
   
$ref        = new ReflectionFunction('array_unshift');
   
$arguments    = func_get_args();
    return       
$ref->invokeArgs(array_merge(array(&$this->arr), $arguments));
}
?>

I don't know about performances (you can create an array manually too, starting from array(&$this->something) and adding arguments). However, it seems to work correctly without problems, at least until the send by reference will be usable with one single value ...
krowork
31-Jan-2008 12:47
Like Will Mason said for the ReflectionMethod's constants, there is filter constants for ReflectionProperty too:

ReflectionProperty::IS_STATIC
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PROTECTED
ReflectionProperty::IS_PRIVATE

that can be used in the ReflectionClass' method getProperties:

$class=new ReflectionClass("Foo");
$class->getProperties(
  ReflectionProperty::IS_STATIC |
  ReflectionProperty::IS_PUBLIC );

this obtains the publics (static or not) and the statics (public or not): this exlude the non static private properties.
annonymous
04-Dec-2007 03:16
If you are getting

Fatal error: Trying to clone an uncloneable object of class ReflectionClass in …

Ensure that this is set.
zend.ze1_compatibility_mode=Off in php.ini

Thanks to anil who posted this on www.tecpages.com
Will Mason
03-Aug-2007 11:29
If you are looking for the long $filters for ReflectionClass::getMethods(), here they are. They took me a  long time to find. Found nothing in the docs, nor google. But of course, Reflection itself was the final solution, in the form of ReflectionExtension::export("Reflection").

<?php
//The missing long $filter values!!!
ReflectionMethod::IS_STATIC;
ReflectionMethod::IS_PUBLIC;
ReflectionMethod::IS_PROTECTED;
ReflectionMethod::IS_PRIVATE;
ReflectionMethod::IS_ABSTRACT;
ReflectionMethod::IS_FINAL;

//Use them like this
$R = new ReflectionClass("MyClass");
//print all public methods
foreach ($R->getMethods(ReflectionMethod::IS_PUBLIC) as $m)
    echo
$m->__toString();
?>
killgecNOFSPAM at gmail dot com
25-Jul-2007 03:53
Signature of constructor of ReflectionParameter correctly is:

public function __construct(array/string $function, string $name);

where $function is either a name of a global function, or a class/method name pair.
massimo at mmware dot it
18-Jul-2007 06:58
I found these limitations using class ReflectionParameter from ReflectionFunction with INTERNAL FUNCTIONS (eg print_r, str_replace, ... ) :

1. parameter names don't match with manual: (try example 19.35 with arg "call_user_func" )
2. some functions (eg PCRE function, preg_match etc) have EMPTY parameter names
3. calling getDefaultValue on Parameters will result in Exception "Cannot determine default value for internal functions"
thiago_mata at yahoo dot com dot br
06-Sep-2006 12:19
If you need to try to do something with the phpdoc or like the java notations in php4, you can create your own
'reflection functions'. This is a litle example of that.
<?php

/**
 * Comment used to start a phpdoc
 * @author Thiago Mata
 * @package notations
 */
define( 'START_DOC' , '/**' );

/**
 * Comment used to end a phpdoc
 * @author Thiago Mata
 * @package notations
 */
define( 'END_DOC' , '*/' );

/**
 * Comment used to indicate a tag of phpdoc
 * @author Thiago Mata
 * @package notations
 */
define( 'TAG_DOC' , '@' );

/**
 * This is a function maded in PHP4 to get the notations from some php file.
 * Can use comments with many lines
 *
 * @author Thiago Mata
 * @date 05/09/2006
 * @package notations
 * @param string $strFile
 * @copyright open source
 * @example <code> $arrNotations = getFileNotations( 'somefile.php' ); </code>
 */
function getFileNotations( $strFile )
{
   
$strText = file_get_contents( $strFile );
   
$arrText = explode( "\n" , $strText );
   
   
$arrNotations = array();
   
    for (
$intCount = 0 ; $intCount < count( $arrText ) ; ++$intCount )
    {
       
$strLine = $arrText[ $intCount ];
       
       
// inside the phpdoc //
       
if ( strpos( trim( $strLine ) , START_DOC ) === 0 )
        {
            ++
$intCount;
           
$strLine = $arrText[ $intCount ];
           
$arrNotation = array();
           
           
// while the phpdoc is not finished //
           
while ( ( strpos( trim( $strLine ) , END_DOC ) !== 0 ) and ( $intCount < count( $arrText ) ) )
            {
               
// removing the tag doc from the line //
               
$strLine = substr( $strLine , strpos( $strLine , TAG_DOC ) );
               
// get the name of the tag //
               
$strName = substr( $strLine , 0 , strpos( $strLine , ' ' ) );
               
// get the value of the tag //
               
$strLine = substr( $strLine , strpos( <