PHP 5 Reflection API performance
Don't be concerned. Install Xdebug and be sure where the bottleneck is.
There is cost to using reflection, but whether that matters depends on what you're doing. If you implement controller/request dispatcher using Reflection, then it's just one use per request. Absolutely negligible.
If you implement your ORM layer using reflection, use it for every object or even every access to a property, and create hundreds or thousands objects, then it might be costly.
Is it bad to use Reflection in production code?
You really shouldn't use Reflection in production code. Why don't you use is_callable
here?
if (!is_callable(array('Validations', $validation_method)) {
throw new LogicException('method does not exist');
}
This checks that the Validations
class has a static method $validation_method
and ensures that you may call it from current context. Actually this gives you even more flexibility then reflection, because this takes __call
methods and similar stuff into account that Reflection doesn't.
Reflection::hasMethod vs. method_exists performance
I measured it with 1,000,000 loops. It may be not representative.
Needed 21 seconds:
$reflector = new ReflectionClass($module);
$reflector->hasMethod('getDecryptedId'))
Needed 1.2 seconds:
method_exists($module, 'getDecryptedId')
So method_exists is 17.5 times faster. This only is interresting, if you do massive use of it.
What is the Reflection class for?
It appears this class exists specifically for its export()
method, without implementing the Reflector
interface.
From PHP 5 Recipes (found with a slightly annoying Google search):
Reflection
: This class implements as a static method theexport()
method defined byReflector
, although it does not actually implement theReflector
interface. You can use this method to dump all the methods and/or properties of a class, extension, property, method or parameter.
Reflection or dynamic methods
There is a bug in PHP that prevents scalar type declarations to be interpreted strictly when a function or method is invoked using the Reflection API.
Example:
class C
{
public function m(string $x)
{
var_dump($x);
}
}
Calling via reflections (don't do this!)
declare(strict_types=1);
$object = new C();
$arguments = [1];
$method = new ReflectionMethod($object, 'm');
$method->invokeArgs($object, $arguments);
The result:
string(1) "1"
Conclusion: Don't use Reflection to invoke a method.
Source
PHP: Performance: splat operator or reflection
Definitely go for the splat operator, why? It's much faster than the reflection approach (I'm using it and the implementation seems to be very good). Also reflection breaks just about anything that has to do with design, it allows you to break encapsulation for instance.
PS: Isn't it $instance = new $class(...$args);
?
PHP: The Reflection API - Great Addition To PHP With Little Use
Reflection is definitely here to stay. You may use it, but keep in mind it is said to be slow and overkill for simple UseCases. Using one of the functions in the Classes/Objects function package is often the faster alternative.
A UseCase where Reflection comes in handy is when parsing for annotations in the DocBlock of a class. For instance, PHPUnit uses the annotations @test to tell the PHPUnit TestRunner that it should consider a method a test. The @covers annotation will help it collect Code Coverage data. The FLOW3 framework makes use of Annotations for their AOP framework.
Unfortunately, some of the newer additions to PHP > 5.3, are not documented yet that much. Just look at the SPL. Same thing. That doesn't mean you cannot use it though. The Reflection API is very expressive and easy to figure out from the method names. And Google often has blog posts about how to use certain extensions. For the Reflection API, check out:
- http://www.phpriot.com/articles/reflection-api
- http://mark-story.com/posts/view/using-the-php-reflection-api-for-fun-and-profit
- http://www.tuxradar.com/practicalphp/16/4/0
- http://weierophinney.net/matthew/archives/125-PHP-5s-Reflection-API.html
and for SPL
- http://www.phpro.org/tutorials/Introduction-to-SPL.html
Something cool I just discovered recently. As of 5.1.2, you can invoke the Reflection API from the command line too:
$php --rf strtotime
Function [ <internal:date> function strtotime ] {
- Parameters [2] {
Parameter #0 [ <required> $time ]
Parameter #1 [ <optional> $now ]
}
}
Getting runtime properties with ReflectionClass
ReflectionClass::getProperties() gets only properties explicitly defined by a class. To reflect all properties you set on an object including dynamic properties, use ReflectionObject which inherits from ReflectionClass and works on runtime instances:
$reflect = new ReflectionObject($this);
Using chosen methods with Reflection class
Haven't tried this, but something like
$total_rating += $method->invoke($this);
So $method
is the reflection method object from your loop (and the result of getMethods
) and you pass in the object which you want to invoke the method on.
(from example on manual page https://www.php.net/manual/en/reflectionmethod.invoke.php#refsect1-reflectionmethod.invoke-examples)
Related Topics
Enabling Cors in Codeigniter ( Restserver by @Chriskacerguis )
Fatal Error: Allowed Memory Size of 268435456 Bytes Exhausted (Tried to Allocate 71 Bytes)
How to Get the External Ip of My Server Using PHP
How to Iterate Through Dom Elements in PHP
How to Convert Utc Datetime to Another Timezone
MySQL Table Does Not Exist Error, But It Does Exist
PHP & Hash/Fragment Portion of Url
Laravel Many to Many Self Referencing Table Only Works One Way
Utf-8 Problems While Reading CSV File with Fgetcsv
How to Use PHPunit to Test a Function If That Function Is Supposed to Kill PHP
Split an Array into N Arrays - PHP
How to Loop Through JSON Array
How to Insert into MySQL Using a Prepared Statement with PHP
Get Only Filename from Url in PHP Without Any Variable Values Which Exist in the Url