I've a soap function which expects 3 parameters that should be passed as strings with quotes.
function('id','username','password');
and in another hand i've an array which contains :
[0] = > "'id','username','password'"
[1] = > "'id','username','password'"
....
when i echo $array[0] out put is 'id','username','password' and when i use function('id','username','password'); there is no problem but when i use
function($array[0]); it won't work.
i tested my array with echo, die, print_r ... the output is the same as the function expects!!!!
any help ?
thanks ; )
Simply because it can't work. If you have a function that needs 3 parameters, you can't pass a single parameter. Also if is an array that contains the 3 parameters you need, the function still want and need 3 parameters. Thus, if you give the function an array, it will use just the array as the first one (so you'll have an unexpected behavior) and take the second and the thirs as NULL.
It's true that php is a little bit magic, but can't do miracles.
You need to change the signature of your function.
function('id','username','password');
is a function with three parameters.
function($array[0]);
is a function with only one parameter.
Related
I'm kinda confused about optional parameters, or setting a parameter within the function in general. So I found this example:
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
and I don't understand why echo makecoffe("espresso") returns espresso and not cappuccino. Wouldn't espresso be overwritten when calling the method? In my head $type would first be espresso but would then be set to cappuccino since it happens after calling the method. It's kind of hard to explain what I mean, but does $type = "cappuccino" only get called when there's no parameter or why does this happen? Same with
function makecoffee($type = null)
{
}
echo makecoffe("espresso");
why would this return espresso and not null even though type would be set to null when calling the function?
Good example to inform you how exactly the php parameters in functions works, would be the func_get_args() which returns all passed arguments to function.
And this will be our example function.
function foo($example = 'default')
{
print_r(func_get_args());
}
Now we can check if any argument was passed to function.
What happens if we don't pass any argument?
foo();
// Output
Array
(
)
We know that function was called without any argument because output array is empty.
And that is the moment where default value is used for our function parameter. So finally the value for $example parameter will be equal to 'default'
Now we will try to pass 2 arguments to function.
foo('example', 'unnecessary');
// Output
Array
(
[0] => example
[1] => unnecessary
)
From this example we can deduce that we can pass any amount of arguments without seeing an exception. This is one of php features.
But which was passed to $example parameter?
As php docs informs.
The arguments are evaluated from left to right.
The left side for our example is the value from an array with index 0 and the right side is the last element with (actually index 1)
So, under $example we well have 'example' value.
In defaults, the second argument will be ignored because our function doesn't have corresponding second parameter.
What if we pass null as a argument?
This may be tricky because we can imagine that function called with null as a argument will affect on our function as function called without any arguments.
Nothing more wrong.
foo(null);
// Output
Array
(
[0] =>
)
Now you should see that. Despite the fact that our argument was null, value was passed into our function and overwrited default 'example' value for parameter. Finally $example parameter will be equal to null.
That's because the $param = 'value' bit in the function declaration is not executed every time the function is called.
It only comes into play if you don't pass a value for that parameter.
Instead of reading it as a literal assignment PHP does something along the lines of the following under the hood whenever it enters your function.
if true === $param holds no value
$param = 'value'
endif
In other words, $param = 'value' is not a literal expression within the context of the language but rather a language construct to define the desired behaviour of implementing fallback default values.
Edit: Note that the snippet above is deliberately just pseudo code as it's tricky to accurately express what's going using PHP on once PHP has been compiled. See the comments for more info.
I want to be able to call a php function, but only if the number of elements input, matches the number of elements accepted by the function and if it does match i want to pass them 1 by 1 and not as an array.
Currently i have the following code which does the job, but is messy.
call_user_func($functionname, $vars);
This was hitting problems when i had a function that expected an array of 4 elements, but was only passed 3. Having to check and make sure all the vars exist makes writing functions a bit messy. I have a better solution based on reflection. how to dynamically check number of arguments of a function in php , but im one final step short. If the number of arguments matches the number of arguments in a function, i can call that method, but i dont know how to call that method correctly. I have an array of variables. I need to pass these into the function so that I can do something like the following.
function foo($var1, $var2, $var3)
{
//I know all 3 vars exist and dont need to verify first
}
if(count($arrayof3elements) == get_method_var_count("foo") {
dynamically_call_method("foo", $arrayof3elements);
}
Instead of using call_user_func, use call_user_func_array - this allows you to pass an array of arguments, but passes them to the method as separate things.
function x($foo, $bar) {
echo $foo . $bar;
}
call_user_func_array('x', ['abc', 'def']); // prints abcdef
Bear with me, I'm learning.
I often see snippets like the one below:
<?p
$imageArray = get_field('image_field');
$imageAlt = $imageArray['alt'];
$imageURL = $imageArray['url'];
?>
It is pedagogical and clear and organized. But is it necessary to get the entire array before querying the array for values? Can I not define the variable in just a single line? Something like the below (which doesn't work, neither the other variants I have tried):
$imageAlt = get_field('image_field', ['alt']);
$imageURL = get_field('image_field', ['url']);
Yes, you can.
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable. - Source
$imageAlt = get_field('image_field')['alt'];
https://eval.in/548036
The question you are asking can be answered by asking 2 questions:
Is it doable ?
Is it a good idea to do it that way ?
Is it doable ?
Yes! You do not have to store the array in a variable and re-use it later.
For instance, you could do:
$imageAlt = get_field('image_field')['alt'];
Note: This will work in PHP 5.4+ and is called: Array dereferencing.
But that is not the only consideration...
Is it a good idea to do it that way ?
No. It's not a good idea in many cases. The get_field() function, depending on your context, is probably doing a lot of work and, each time you call it, the same work is don multiple times.
Let's say you use the count() function. It will count the number of items in an array. To do that, it must iterate through all items to get the value.
If you use the count() function each time you need to validate number of items in an array, you are doing the task of counting each and every time. If you have 10 items in your array, you probably won't notice. But if you have thousands of items in your array, this may cause a delay problem to compute your code (a.k.a. it will be slow).
That is why you would want to do something like: $count = count($myArray); and use a variable instead of calling the function.
The same applies to your question.
While PHP 5.4+ allows you to directly dereference a function return value like this:
get_field('image_field')['alt']
...in this particular case I would not suggest you do so, since you're using two values from the resulting array. A function call has a certain overhead just in itself, and additionally you don't know what the function does behind the scenes before it returns a result. If you call the function twice, you may incur a ton of unnecessary work, where a single function call would have done just as well.
This is not to mention keeping your code DRY; if you need to change the particulars of the function call, you now need to change it twice...
PHP allows you to play around quite a bit:
function foo(){
return array('foo' => 1, 'bar' => 2);
}
Option 1
echo foo()['foo']; // 1
# Better do this if you plan to reuse the array value.
echo ($tmp = foo())['foo']; // 1
echo $tmp['bar']; // 2
It is not recommended to call a function that returns an array, to specifically fetch 1 key and on the next line doing the same thing.
So it is better to store the result of the function in a variable so you can use it afterwards.
Option 2
list($foo, $bar) = array_values(foo());
#foo is the first element of the array, and sets in $foo.
#bar is the second element, and will be set in $bar.
#This behavior is in PHP 7, previously it was ordered from right to left.
echo $foo, $bar; // 12
Option 3
extract(foo()); // Creates variable from the array keys.
echo $foo, $bar;
extract(get_field('image_field'));
echo $alt, $url;
Find more information on the list constructor and extract function.
I'm currently looking for a way to give arguments to a function dynamically.
Some code to explain:
//Class: ClassXY
PUBLIC function function1($arg1, $arg2, $arg3);
PUBLIC function function2($arg1);
I currently call it like this:
// $method = 'function1' or 'function2'
echo ClassXY :: {$method}($parameter_string);
My problem is, that parameter_string either is a simple string, that contains the argument or an array that contains all the arguments I want to give to the function. For instance:
$parameter_string: array(3) {[0] => 'arg1', [1] => 'arg2', [2] => 'arg3' }
So far so good. My Problem is, that the call will only work with ClassXY :: function2() since it only expects one argument. If I call ClassXY :: function2() it wont work, since it expects three arguments but only one argument (the array with the three elements, that are supposed to be the three arguments) is given. I need a way to make php realize that each element of the array shall be one argument. Any Ideas?
Thanks in advance!
It looks like call_user_func_array is what you need.
http://php.net/manual/en/function.call-user-func-array.php
OK, I know it sounds weird but I need to make a function that will receive two parameters the first one is a string and the second an array (containing strings).
This function will then call sprintf. My first parameter will be $format and my array will correspond to the various $args.
How can I achieve this (if possible)?
Thanks!
Well you want the vsprintf() function.
Like Orbling answered, for this particular case you need vsprintf.
But, in a generic case, to call a function with variable number of parameters, you can use func_get_args() inside the function which you desire to accept multiple (any number of variable arguments). This function (when called inside your function) returns an array containing all the parameters passed while calling your function.