note 66121 added to function.call-user-func-array

From: Date: Mon, 15 May 2006 09:43:06 +0000
Subject: note 66121 added to function.call-user-func-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-111310@lists.php.net to get a copy of this message
For those wishing to implement call-by-name functionality in PHP, such as implemented e.g. in DB apis, here's a quick-n-dirty version for PHP 5 and up <?php /** * Call a user function using named instead of positional parameters. * If some of the named parameters are not present in the original function, they * will be silently discarded. * Does no special processing for call-by-ref functions... * @param string $function name of function to be called * @param array $params array containing parameters to be passed to the function using their name (ie array key) */ function call_user_func_named($function, $params) { // make sure we do not throw exception if function not found: raise error instead... // (oh boy, we do like php 4 better than 5, don't we...) if (!function_exists($function)) { trigger_error('call to unexisting function '.$function, E_USER_ERROR); return NULL; } $reflect = new ReflectionFunction($function); $real_params = array(); foreach ($reflect->getParameters() as $i => $param) { $pname = $param->getName(); if ($param->isPassedByReference()) { /// @todo shall we raise some warning? } if (array_key_exists($pname, $params)) { $real_params[] = $params[$pname]; } else if ($param->isDefaultValueAvailable()) { $real_params[] = $param->getDefaultValue(); } else { // missing required parameter: mark an error and exit //return new Exception('call to '.$function.' missing parameter nr. '.$i+1); trigger_error(sprintf('call to %s missing parameter nr. %d', $function, $i+1), E_USER_ERROR); return NULL; } } return call_user_func_array($function, $real_params); } ?> ---- Server IP: 213.92.11.19 Probable Submitter: 85.20.248.12 (proxied: 1.1 DMZ01614270) ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.call-user-func-array.php Edit -- http://master.php.net/note/edit/66121 Del: integrated -- http://master.php.net/note/delete/66121/integrated Del: useless -- http://master.php.net/note/delete/66121/useless Del: bad code -- http://master.php.net/note/delete/66121/bad+code Del: spam -- http://master.php.net/note/delete/66121/spam Del: non-english -- http://master.php.net/note/delete/66121/non-english Del: in docs -- http://master.php.net/note/delete/66121/in+docs Del: other reasons-- http://master.php.net/note/delete/66121 Reject -- http://master.php.net/note/reject/66121 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#111310) next »