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.
Related
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
I was wondering if there is any difference when setting default array value to be an empty array or NULL.
For example:
function arrayTest(array $array = array()) {
if(!empty($array)) {
// Do something
}
}
or
function arrayTest(array $array = NULL) {
if(!empty($array)) {
// Do something
}
}
What I noticed is that first example doesn't allow NULL values to be passed and the second example does because of type casting.
Any other differences? Which one should be used?
The other difference is that if you don't pass an argument , it will default to array() or null, which are two very distinct values. You can check for that of course, but you will need to take it into account. empty will work for both, but a foreach loop over null won't work that well, and various array functions will also fail.
What you noticed is correct: Passing null for a typehinted argument only works if you add = null to the declaration. This is not only true for arrays but for objects as well. In PHP there is no way in PHP to make a typehinted argument that is mandatory but can be null. As soon as you add =null to the declaration, you can pass null but you can also omit the parameter.
If to you there is no logical difference between an empty array or null, I would choose the first method of defaulting to an empty array. Then at least you'll know that the input is always an array. I think that add clarity to both the implementer of the function and the programmer(s) who use it. But I guess that's just an opinion and not even a strong one.
My main advice would be to not make the argument optional at all. In my experience this will make the usage of such functions unclear, especially as the code grows and more arguments are added.
Could someone please explain what is going on here in this code?
I can see it is an array called b accessing an element with the key 'c', but the stuff in the brackets? I don't know what is going on here.
$a=$b['c']($d,$e,$f);
$b['c'] must be a function name.
try to print it, you'll see.
$a=$b['c']($d,$e,$f);
calls that function passing $d, $e and $f arguments to it.
Try :
<?php
$func = 'var_dump';
$foo = array(1,2,3);
$func($foo)
It looks like you are looking at a variable function.
The expression above first evaluates the associative array $a=$b['c'] and then calls the function with that name, passing the arguments $d,$e,$f.
From the description:
PHP supports the concept of variable functions. This means that if a
variable name has parentheses appended to it, PHP will look for a
function with the same name as whatever the variable evaluates to, and
will attempt to execute it. Among other things, this can be used to
implement callbacks, function tables, and so forth.
It seems element at key c is expected to be a function.
In PHP5, you can use this kind of short notations. The function will be called with parameters d e and f.
I've looked at Is it possible to pass parameters by reference using call_user_func_array()?, and http://php.net/manual/en/function.call-user-func-array.php. The approved technique for passing by reference using call_user_func_array() seems to be by making the parameter array an array of variable references. For example, setting $parameters = array( &$some_variable). My question is, can we instead make the parameter array an array of variables (not references), and pass the whole parameter array as a reference instead? This is illustrated below:
function toBeCalled( &$parameter1, $parameter2 ) {
//...Do Something...
}
$changingVar = 'passThis';
$changingVar2 = 'passThisToo';
$parameters = array( $changingVar, $changingVar2 );
call_user_func_array( 'toBeCalled', &$parameters );
Notice that the function toBeCalled expects the first variable as a reference, and the second as a value. The reason I ask is because the syntax here is convenient, and it seems to work (see this PHP 5.3 patch for the DruTex module for Drupal - http://drupal.org/node/730940#comment-4054054), but I'm just checking what experts think about it.
You can't, because the moment you put things into an array not by reference, they are copied. So no matter what you do with the array afterwards, it will not affect the original variables you put in (if they were even variables to start with).
The thing you linked to doesn't seem to be relevant. It is removing a pointless call-time pass-by-reference.
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.