|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-08-01 11:24 UTC] benjamin dot morel at strictcoding dot co dot uk
Description: ------------ When ReflectionParameter::isOptional() returns false, because other parameters after it are required, isDefaultValueAvailable() always return false, even is there actually is a default value. I've read this older bug report: https://bugs.php.net/bug.php?id=41382 It looks like at that time, this behaviour had been considerer consistent. I do think this should be revisited however, as in the example function below, there is absolutely no way with Reflection to get the default value for the given parameter. Reflection is a powerful tool for autowiring in Dependency Injection containers, where it is interesting to check whether default parameters are available, regardless of their order. Test script: --------------- function test(PDO $a = null, $b = 0, array $c) {} $r = new ReflectionFunction('test'); foreach ($r->getParameters() as $p) { echo $p->getName(); echo " isDefaultValueAvailable: " . var_export($p->isDefaultValueAvailable(), true) . "\n"; echo " isOptional: " . var_export($p->isOptional(), true) . "\n"; echo " allowsNull: " . var_export($p->allowsNull(), true) . "\n"; echo "\n"; } Expected result: ---------------- a isDefaultValueAvailable: true isOptional: false allowsNull: true b isDefaultValueAvailable: true isOptional: false allowsNull: true c isDefaultValueAvailable: false isOptional: false allowsNull: false Actual result: -------------- a isDefaultValueAvailable: false isOptional: false allowsNull: true b isDefaultValueAvailable: false isOptional: false allowsNull: true c isDefaultValueAvailable: false isOptional: false allowsNull: false PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 03:00:01 2025 UTC |
Thanks for the quick fix, isDefaultValueAvailable() works indeed, but getDefaultValue() still throws an exception: <?php function test(PDO $a = null, $b = 0, array $c) {} $r = new ReflectionFunction('test'); foreach ($r->getParameters() as $p) { if ($p->isDefaultValueAvailable()) { var_export($p->getDefaultValue()); } } Fatal error: Uncaught exception 'ReflectionException' with message 'Parameter is not optional'