|
| 1 | +[<-- Return to index](../README.md) |
| 2 | +# Reflection |
| 3 | + |
| 4 | +### What reflection abilities are supported? |
| 5 | +#### PHP |
| 6 | +PHP will automatically use inspection at runtime to determine, for example, if an object being called has a particular method implemented, or that a particular object's method exists if it is being called. |
| 7 | +#### Python |
| 8 | +Python has several inspection methods built natively into the language. These include: |
| 9 | + * [callable()](https://docs.python.org/3/library/functions.html#callable): returns `True` if the provided object can be called. |
| 10 | + * [type()](https://docs.python.org/3/library/functions.html#type): returns the type of the object provided. |
| 11 | + * [isinstance](https://docs.python.org/3/library/functions.html#isinstance): takes two objects as arguments, and will return `True` if the first object provided is an instance of the second. |
| 12 | + * [dir](https://docs.python.org/3/library/functions.html#dir): returns a list of valid attributes for a provided object. |
| 13 | + * [getattr()](https://docs.python.org/3/library/functions.html#getattr): attempts to return the value of a provided attribute from a provided object |
| 14 | + |
| 15 | +### How is reflection used? |
| 16 | +#### PHP |
| 17 | +By use of a [`ReflectionClass`](https://secure.php.net/manual/en/class.reflectionclass.php) object. You may pass an object's name to an object of this type at creation time to allow inspection of various attributes or conditions of a class. For example, the following will provide a list of available methods for a class called `myClass`: |
| 18 | +```php |
| 19 | +<?php |
| 20 | + class myClass { |
| 21 | + function foo() { |
| 22 | + print "Foo method"; |
| 23 | + } |
| 24 | + function bar($baz) { |
| 25 | + print "Bar method"; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + $reflector = new ReflectionClass('myClass'); |
| 30 | + var_dump($reflector->getMethods()); |
| 31 | +?> |
| 32 | +``` |
| 33 | +will yield: |
| 34 | +``` |
| 35 | +array(2) { |
| 36 | + [0]=> object(ReflectionMethod)#3 (2) { |
| 37 | + ["name"]=> string(3) "foo" |
| 38 | + ["class"]=> string(7) "myClass" |
| 39 | + } |
| 40 | + [1]=> object(ReflectionMethod)#4 (2) { |
| 41 | + ["name"]=> string(3) "bar" |
| 42 | + ["class"]=> string(7) "myClass" |
| 43 | + } |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +#### Python |
| 48 | +Various object details can be determined by using the above described and linked reflection method programmatically. For example, to see if an object is an instance of a given class: |
| 49 | +```python |
| 50 | +class myClass: |
| 51 | + def foo(self): |
| 52 | + print("foo") |
| 53 | + |
| 54 | +a = myClass() |
| 55 | + |
| 56 | +>>>print(isInstance(a, myClass)) |
| 57 | +True |
| 58 | +``` |
0 commit comments