I know that it is possible to call a function with a variable number of parameters with call_user_func_array() found here -> http://php.net/manual/en/function.call-user-func-array.php . What I want to do is nearly identical, but instead of a function, I want to call a PHP class with a variable number of parameters in it's constructor.
It would work something like the below, but I won't know the number of parameters, so I won't know how to instantiate the class.
<?php
//The class name will be pulled dynamically from another source
$myClass = '\Some\Dynamically\Generated\Class';
//The parameters will also be pulled from another source, for simplicity I
//have used two parameters. There could be 0, 1, 2, N, ... parameters
$myParameters = array ('dynamicparam1', 'dynamicparam2');
//The instantiated class needs to be called with 0, 1, 2, N, ... parameters
//not just two parameters.
$myClassInstance = new $myClass($myParameters[0], $myParameters[1]);
You can do the following using ReflectionClass
$myClass = '\Some\Dynamically\Generated\a';
$myParameters = array ('dynamicparam1', 'dynamicparam2');
$reflection = new \ReflectionClass($myClass);
$myClassInstance = $reflection->newInstanceArgs($myParameters);
PHP manual: http://www.php.net/manual/en/reflectionclass.newinstanceargs.php
Edit:
In php 5.6 you can achieve this with Argument unpacking.
$myClass = '\Some\Dynamically\Generated\a';
$myParameters = ['dynamicparam1', 'dynamicparam2'];
$myClassInstance = new $myClass(...$myParameters);
I implement this approach a lot when function args are > 2, rather then end up with an Christmas list of arguments which must be in a specific order, I simply pass in an associative array. By passing in an associative array, I can check for necessary and optional args and handle missing values as needed. Something like:
class MyClass
{
protected $requiredArg1;
protected $optionalArg1;
public function __construct(array $options = array())
{
// Check for a necessary arg
if (!isset($options['requiredArg1'])) {
throw new Exception('Missing requiredArg1');
}
// Now I can just localize
$requiredArg1 = $options['requiredArg1'];
$optionalArg1 = (isset($options['optionalArg1'])) ? $options['optionalArg1'] : null;
// Now that you have localized args, do what you want
$this->requiredArg1 = $requiredArg1;
$this->optionalArg1 = $optionalArg1;
}
}
// Example call
$class = 'MyClass';
$array = array('requiredArg1' => 'Foo!', 'optionalArg1' => 'Bar!');
$instance = new $class($array);
var_dump($instance->getRequiredArg1());
var_dump($instance->getOptionalArg1());
I highly recommend using an associative array, however it is possible to use a 0-index array. You will have to be extremely careful when constructing the array and account for indices that have meaning, otherwise you will pass in an array with offset args and wreck havoc with your function.
You can do that using func_get_args().
class my_class {
function __construct( $first = NULL ) {
$params = func_get_args();
if( is_array( $first ) )
$params = $first;
// the $params array will contain the
// arguments passed to the child function
foreach( $params as $p )
echo "Param: $p\n";
}
}
function my_function() {
$instance = new my_class( func_get_args() );
}
echo "you can still create my_class instances like normal:";
$instance = new my_class( "one", "two", "three" );
echo "\n\n\n";
echo "but also through my_function:";
my_function( "one", "two", "three" );
Basically, you simply pass the result of func_get_args to the constructor of your class, and let it decide whether it is being called with an array of arguments from that function, or whether it is being called normally.
This code outputs
you can still create my_class instances like normal:
Param: one
Param: two
Param: three
but also through my_function:
Param: one
Param: two
Param: three
Hope that helps.
I've found here
Is there a call_user_func() equivalent to create a new class instance?
the example:
function createInstance($className, array $arguments = array())
{
if(class_exists($className)) {
return call_user_func_array(array(
new ReflectionClass($className), 'newInstance'),
$arguments);
}
return false;
}
But can somebody tell me if there is an example for classes with protected constructors?
Related
I'm using reflection to dynamically call methods.
$object = new $class;
$reflector = new ReflectionMethod($class, $method);
$reflector->invokeArgs($object, $arguments);
The $arguments array looks like:
Array
(
[fooparam] => false
[id] => 238133
)
The method called could be:
class MyClass
{
public function myMethod ($id, $fooParam)
{
// Whatever
}
}
The problem is that everything comes from frontend designers, depending on data-* attributes, href... so $arguments array has arbitrary sorting.
How can I sort this array to match method parameters?
O maybe, is there a better solution? Named parameters?
Use ReflectionMethod::getParameters() to get a list of arguments and filter map them to their corresponding position, e.g.:
$sorted_args = array_map(function($param) use($arguments) {
$name = $param->getName();
if (!isset($arguments[$name]) && !$param->isOptional())
throw new BadMethodCallException("Argument '{$name}' is mandatory");
return isset($arguments[$name]) ? $arguments[$name] : $param->getDefaultValue();
}, $reflector->getParameters());
You could also use a simple foreach loop, it's up to you.
Then invoke the method with $sorted_args instead:
$reflector->invokeArgs($object, $sorted_args);
I want to call an object method+property with the content stored in a var ...
for example :
// setup the object
$xpath = new DOMXpath();
// setup the 'method'+'property' to call
$var1 = "query('something')->item(O)->nodeValue";
$return = $xpath->$var1();
Obviously, I make a mistake ... assuming that direct call is working, i.e.:
$return2 = $xpath->query('something')->item(0)->value;
echo "Return2 : ".$return2; //print okeedokee ...
How to pass args to query()? And how to add extra args to it?
I think you have to call
$return=$xpath->$var1;
Note : call_user_func is the function you need
Example :
alpha.php
class Alpha
{
public function getAlpha($arr_input)
{
echo "<pre>";
print_r($arr_input);
}
}
index.php
include_once 'alpha.php';
$post = array('one','two','three');
$obj_alpha = new Alpha();
call_user_func( array( $obj_alpha , 'getAlpha' ), $post ) ;
//here I call `getAlpha` function from object of class alpha (`$obj_alpha`)
with argument `$post`
//will print $post array
You can do this using eval():
$return = eval('return $xpath->' . $var1 .';');
However, using eval() with user-input is pretty much always a bad idea. So be careful there.
I have a function which takes in about 10 arguments, in which most of them are optional. I was wondering if I could implement it in such a way that the user of the function does not need to bother with the order of the parameters.
For example:
public function foo($arg1, $arg2, $arg3='',$arg4='', $arg5='', $arg6='', $arg7=''){}
Now, when I use this function I can simply
$this->foo($arg1val, $arg2val, $arg6val);
Is there a way in php to do so?
Here is how I implemented this:
I've listed the parameters accepted by the function in the API, so the user can pass the parameters in any order in an array with key=>value pairs.
For example:
public function argumentsFilter($origParams, $newParams){
$tmpArr = array();
foreach ($origParams as $origKey){
foreach($newParams as $newKey => $newVal){
if($newKey == $origKey){
$tmpArr[$origKey] = $newVal;
}
}
if(empty($tmpArr[$origKey])){
$tmpArr[$origKey] = '';
}
}
return $tmpArr;
}
public function foo($arg1, $arg2, $arg=array()){
$validArgList = array('arg3', 'arg4', 'arg5', 'arg6', 'arg7');
$correctedArgList = $this->argumentsFilter($validArgList, $arg);
}
Is there a more elegant way to do this?
10 parameters for a function is clearly too much. Pass arrays instead:
function foo(array $params) {
$defaults = array('foo' => true, 'bar' => false, ...);
$params = array_intersect_key($params, $defaults) + $defaults;
// work with $params['foo']
// maybe extract($params)
}
This example shows a function that accepts an arbitrary number of "named parameter" in any order, filters invalid values and establishes defaults values.
It is not possible, since php doesn't support named arguments.
You have 2 choices: to use array or to redesign your function so it has fewer parameters (the latter is preferred).
There are many ways to do that, but I recommend this method:
function doSomething($required, /*optional*/ $arguments = array()) {
$arguments = array_merge(array(
// set defaults
"argument" => "default value",
), $arguments);
var_dump($arguments);
}
It is very clean and easy to understand.
I will explain the question with a simple function accepting any number of function
function abc() {
$args = func_get_args();
//Now lets use the first parameter in something...... In this case a simple echo
echo $args[0];
//Lets remove this first parameter
unset($args[0]);
//Now I want to send the remaining arguments to different function, in the same way as it received
.. . ...... BUT NO IDEA HOW TO . ..................
//tried doing something like this, for a work around
$newargs = implode(",", $args);
//Call Another Function
anotherFUnction($newargs); //This function is however a constructor function of a class
// ^ This is regarded as one arguments, not mutliple arguments....
}
I hope the question is clear now, what is the work around for this situation?
Update
I forgot to mention that the next function I am calling is a constructor class of another class.
Something like
$newclass = new class($newarguments);
for simple function calls
use call_user_func_array, but do not implode the args, just pass the array of remaining args to call_user_func_array
call_user_func_array('anotherFunction', $args);
for object creation
use: ReflectionClass::newInstanceArgs
$refClass = new ReflectionClass('yourClassName');
$obj = $refClass->newInstanceArgs($yourConstructorArgs);
or: ReflectionClass::newinstance
$refClass = new ReflectionClass('yourClassName');
$obj = call_user_func_array(array($refClass, 'newInstance'), $yourConstructorArgs);
When trying to call a function in a child class with an arbitrary set of parameters, I'm having the following problem:
class Base{
function callDerived($method,$params){
call_user_func_array(array($this,$method),$params);
}
}
class Derived extends Base{
function test($foo,$bar){
print "foo=$foo, bar=$bar\n";
}
}
$d = new Derived();
$d->callDerived('test',array('bar'=>'2','foo'=>1));
Outputs:
foo=2, bar=1
Which... is not exactly what I wanted - is there a way to achieve this beyond re-composing the array with the index order of func_get_args? And yes, of course, I could simply pass the whole array and deal with it in the function... but that's not what I want to do.
Thanks
No. PHP does not support named parameters. Only the order of parameters is taken into account. You could probably take the code itself apart using the ReflectionClass to inspect the function parameter names, but in the end you'd need to use this to reorder the array anyway.
The stock PHP class ReflectionMethod is your friend.
Example:
class MyClass {
function myFunc($param1, $param2, $param3='myDefault') {
print "test";
}
}
$refm = new ReflectionMethod('MyClass', 'myFunc');
foreach ($refm->getParameters() as $p)
print "$p\n";
And the result:
Parameter #0 [ <required> $param1 ]
Parameter #1 [ <required> $param2 ]
Parameter #2 [ <optional> $param3 = 'myDefault' ]
At this point you know the names of the parameters of the target function. With this information you can modify your method 'callDerived', and you can re-order the array to call_user_func_array according to the parameter names.
Good news, I had the same concern (I was looking for named arguments in PHP, like Python does), and found this useful tool : https://github.com/PHP-DI/Invoker
This uses the reflection API to feed a callable with some arguments from an array and also use optional arguments defaults for other parameters that are not defined in the array.
$invoker = new Invoker\Invoker;
$result = $invoker->call(array($object, 'method'), array(
"strName" => "Lorem",
"strValue" => "ipsum",
"readOnly" => true,
"size" => 55,
));
Have fun
UPDATE: PHP 8 Now supports named parameters. And it works with call_user_func_array if you pass an associative array. So you can simply do this:
<?php
function myFunc($foo, $bar) {
echo "foo=$foo, bar=$bar\n";
}
call_user_func_array('myFunc', ['bar' => 2, 'foo' => 1]);
// Outputs: foo=1, bar=2
In your code, you'll be happy to know that you don't have to change a thing. Just upgrade to PHP 8 and it'll work as you expected
You can simply pass an array and extract:
function add($arr){
extract($arr, EXTR_REFS);
return $one+$two;
}
$one = 1;
$two = 2;
echo add(compact('one', 'two')); // 3
This will extract as references, so there is close to no overhead.
I use a bitmask instead of boolean parameters:
// Ingredients
define ('TOMATO', 0b0000001);
define ('CHEESE', 0b0000010);
define ('OREGANO', 0b0000100);
define ('MUSHROOMS', 0b0001000);
define ('SALAMI', 0b0010000);
define ('PEPERONI', 0b0100000);
define ('ONIONS', 0b1000000);
function pizza ($ingredients) {
$serving = 'Pizza with';
$serving .= ($ingredients&TOMATO)?' Tomato':'';
$serving .= ($ingredients&CHEESE)?' Cheese':'';
$serving .= ($ingredients&OREGANO)?' Oregano':'';
$serving .= ($ingredients&MUSHROOMS)?' Mushrooms':'';
$serving .= ($ingredients&SALAMI)?' Salami':'';
$serving .= ($ingredients&ONIONS)?' Onions':'';
return trim($serving)."\n" ;
}
// Now order your pizzas!
echo pizza(TOMATO | CHEESE | SALAMI);
echo pizza(ONIONS | TOMATO | MUSHROOMS | CHEESE); // "Params" are not positional
For those who still might stumble on the question (like I did), here is my approach:
since PHP 5.6 you can use ... as mentioned here:
In this case you could use something like this:
class Base{
function callDerived($method,...$params){
call_user_func_array(array($this,$method),$params);
}
}
class Derived extends Base{
function test(...$params){
foreach ($params as $arr) {
extract($arr);
}
print "foo=$foo, bar=$bar\n";
}
}
$d = new Derived();
$d->callDerived('test',array('bar'=>'2'),array('foo'=>1));
//print: foo=1, bar=2
There is a way to do it and is using arrays (the most easy way):
class Test{
public $a = false;
private $b = false;
public $c = false;
public $d = false;
public $e = false;
public function _factory(){
$args = func_get_args();
$args = $args[0];
$this->a = array_key_exists("a",$args) ? $args["a"] : 0;
$this->b = array_key_exists("b",$args) ? $args["b"] : 0;
$this->c = array_key_exists("c",$args) ? $args["c"] : 0;
$this->d = array_key_exists("d",$args) ? $args["d"] : 0;
$this->e = array_key_exists("e",$args) ? $args["e"] : 0;
}
public function show(){
var_dump($this);
}
}
$test = new Test();
$args["c"]=999;
$test->_factory($args);
$test->show();
a full explanation can be found in my blog:
http://www.tbogard.com/2013/03/07/passing-named-arguments-to-a-function-in-php/