I have the following PHP function:
function func_name($name = 'John', $country = 'USA')
{
do something;
}
And now, am trying to pass variable to the function as follows:
func_name($name = 'Jack', $country = 'Brazil');
I know, we can pass it easily as func_name('jack', 'Brazil'); but the above function is just an example. The actual function has around 20 arguments and all have default values, and some are not at all passed to the function
So I would like to know if its proper to pass arguments as func_name($name = 'Jack', $country = 'Brazil');
No, it's not the right way to do it. foo($bar = 'baz') means you're assigning 'baz' to the variable $bar as usual. This assignment operation results in the value that was assigned, so the expression $bar = 'baz' has the value 'baz'. This value 'baz' gets passed into the function. The functions doesn't have any clue that you have assigned to a variable $bar.
In other words, PHP doesn't support named arguments.
If your function accepts many parameters, all or most of which are optional, use arrays:
function foo(array $args = array()) {
// set default values for arguments not supplied
$args += array('name' => 'John', 'country' => 'USA', …);
// use $args['name'] etc.
// you could do extract($args), then use $name directly,
// but take care not to overwrite other variables
}
foo(array('country' => 'Japan'));
Could you pass in an array?
function something($arr) {
$name = $arr['name'];
}
function something(Array("name"=>"jack", "country"=>"UK"));
Related
In the past few years I've used this formula to read parameters in my methods inside my php classes:
$params = func_get_args();
if(is_array($params[0])){
foreach($params[0] as $key => $value){
${$key} = $value;
}
}
And it works fine, as if I pass something like this:
$class->foo(array('bar' => 'hello', 'planet' => 'world'));
I will have in my foo method the variables bar and planet with their relative values.
But what I'm asking is: Is there any better way to do it? Something that maybe I can encapsulate in another method for example?
UPDATE
So, taking in consideration rizier123 comment, and after a chat with a friend of mine, I nailed down what I think is the better way pass parameters to function. As I know that I will always pass just one parameter to the function, which is always going to be an array, there's no need to call the func_get_args() function, but I better to expect an array all the time and by default I set an empty array, like in the following example:
class MyClass{
public function MyMethod(array $options = array()){
extract($options);
}
}
$my = new MyClass();
$my->MyMethod(array('name' => 'john', 'surname' => 'doe'));
// Now MyMethod has two internal vars called $name and $surname
Yes you can use extract() to convert your arrays to variables, like this:
extract($params[0]);
There is a new feature from PHP 5.6, it's called Variadic functions
http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list
function foo(...$arguments) {
foreach ($arguments as $arg) {
var_dump($arg);
}
}
foo('1', 2, true, new DateTime('now'));
You can do this with PHP built-in function extract().
Use it this way:
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array);
When you run echo $color, $size, $shape; it outputs:
blue, medium, sphere
In Python it is possible to have a function with several variables all having a default value. And then just passing the value of one of the values. So if I have
function foo(a=10,b=50, c=70)
pass
pass
return
Then I can call
foo(b=29)
and it would call
foo(10,29,70)
(using the default for all the values, and the exact value for that one variable).
Is something similar possible in PHP?
No there is no equivalent to that in PHP. You can have default values for function arguments, but they are evaluated from left to right and are not named:
function test($var1 = 'default1', $var2 = 'default2')
{
}
In that example the two variables are optional, but you must specify the first argument if you want to specify the second.
test(); // works
test('arg1'); // works
test('arg1', 'arg2'); // works
test('arg2'); // this will set the first argument, not the second.
A common workaround if you need flexibility on your optional arguments is to pass an array as the argument:
function test($options)
{
}
This can have a variable number of arguments in the form of a single associative array:
$options = array('var1' => 'arg1', 'var2' => 'arg2');
test($options);
Use array as an argument. For example:
function a(array $params) {
$defaults = array(
'a' => 10,
'b' => 50,
'c' => 70,
);
$params += $defaults;
// use $params
}
a(array('b' => 29));
Can pass a value to specific argument in function ?
function fun1($a,$b)
{
echo $b;
}
#fun1(123);
Functions can be defined so that they do not require all parameters. For example:
function foo($a, $b = 2) {
echo $a + $b;
}
foo(1); //gives 3
Read about default function values here
However, you cannot pass in later parameters without specifying earlier ones. Some simple programming-function-parameters-basics... when you do foo($b) the function has no idea that the variable was named b... It just gets the data; usually a primitive type (in this case an int) or a reference.
You haven't specified how you're using these variables, so you may want to give a dummy value like "-1" to $a (and handle it in your function) (foo(-1, 123)), or rewrite your function so that $a is the second parameter with the default value. (function foo($b, $a = NULL))
That's why you must pass the variables in order; the function assumes you're using it right, and it lines up the values passed with the function definition. function foo($a, $b) means "I'm assuming I should associate your first value with a and your second value with b)".
With your original example function foo($a, $b):
No context, so I would just say do this function foo($b, $a = some_default_value). However, I'm assuming you're using $a and $b equally so you could check to see if it was some default-invalid-value and act on it. However, if your function performs different tasks depending on the (number of) parameters passed, you probably want to separate your function.
If you insist on not switching the order, you could call foo(-1, 123) with a dummy value and check it. Again though, same problem as above
Edit: You've given another example foo($a, $b, $c) and you said you want to do foo($b) to update the middle value. See the explanation in the first paragraph about how a function knows what parameter is what.
If you mean you want to pass an arbitrary set of variables to a function and it knows which ones it got? Again I don't think this is the best practice (you'll need to give us more detail about how you're using this) but you could pass an associative array:
function foo($arr) {
if (isset($arr['a'])) {
echo $a;
}
if (isset($arr['b'])) {
echo $b;
}
if (isset($arr['c'])) {
echo $c;
}
}
foo(array('b' => 123));
I feel horrible after writing this function :P
<?php
function FUN1($a, $b)
{
echo "HI";
echo $b;
} //$_a= 123; //error_reporting (E_ALL ^ E_NOTICE ^ E_WARNING); //$b=23; echo #FUN1(123);//it gives HI123
?>
I formatted your function. Firstly, when I tried that call it doesn't give me "HI123". Secondly, # is bad practice and really slows down the code. Thirdly, you don't echo FUN1 since it doesn't return anything; your function prints the stuff itself.
You (your student) are/is going in the wrong direction. As I said in my comment, functions already have a beautiful way of sorting out the parameters. Instead of trying to do something funky and work around that, just change your approach.
The example above has no real use and I'm sure in actual code you should just write different functions when you're setting different variables. like setA($a) setB($b) setC($c) setAll($a, $b, $c) and use them accordingly. Arrays are useful for easy variable length functions, but if you're checking each tag to do something, then something's wrong.
If you only want to pass one argument, you could make a wrapper function like this:
function PassOne($arg)
{
fun1(NULL,$arg);
}
function fun1($a,$b)
{
echo $b;
}
Forgive any inaccuracies. It's been a while since I coded in PHP.
If you want to ensure the order of arguments, you can pass a single array as an argument.
$args = array(
'name' => 'Robert',
'ID' => 12345,
'isAdmin' => true
);
example($args);
function example($args)
{
echo $args['name']; // prints Robert
echo $args['ID']; // prints 12345
echo $args['isAdmin']; // prints true
}
Using this approach, you can also hard-code default values into the function, replacing them only when they're provided in the argument array. Example:
$args = array(
'name' => 'Robert',
'ID' => 12345
// Note that I didn't specify whether Robert was admin or not
);
example($args);
function example($args)
{
$defaultArgs = array(
'name' => '',
'ID' => -1,
'isAdmin' => false // provides a default value to incomplete requests
);
// Create a new, mutable array that's a copy of the default arguments
$mixArgs = $defaultArgs;
// replace the default arguments with what was provided
foreach($args as $k => $v) {
$mixArgs[$k] = $v;
}
/*
Now that we have put all the arguments we received into $mixArgs,
$mixArgs is mix of supplied values and default values. We can use
this fact to our advantage:
*/
echo $mixArgs['name']; // prints Robert
// if ID is still set to the default value, the user never passed an ID
if ($mixArgs['ID'] == -1) {
die('Critical error! No ID supplied!'); // use your imagination
} else {
echo mixArgs['ID']; // prints 12345
}
echo mixArgs['isAdmin']; // prints false
// ... etc. etc.
}
2018's PHP syntax and defaults
function example($args=[], $dftArgs=['name'=>'', 'ID' => -1, 'isAdmin'=>false])
{
if (is_string($args))
$args = json_decode($args,true); // for microservice interoperability
$args = array_merge($dftArgs,$args);
// ... use $args
}
// PS: $dftArgs as argument is not usual, is only a generalization
No.
But by convention you can skip arguments to built in functions by passing NULL in that position:
fun1(NULL, 123);
Obviously this is doesn't make sense for everything - for example this makes no sense:
$result = strpos(NULL, 'a string');
For user defined functions, it's up to you to handle the arguments in whatever way you see fit - but you might find func_get_arg()/func_get_args() useful for functions that use an indeterminate number of arguments.
Also, don't forget you can make arguments optional by defining default values:
function fun ($arg = 1) {
echo $arg;
}
fun(2); // 2
fun(); // 1
Note that default values can only be defined on the right-most arguments. You cannot give an argument a default value if an argument to its right does not have one. So this is illegal:
function fun ($arg1 = 1, $arg2) {
// Do stuff heere
}
When calling a function is there a way to simplify the argument list? Instead of using $blank.
$subscribe=1;
$database->information($blank,$blank,$blank,$blank,$blank,$blank,$subscribe,$blank,$blank,$blank,$blank,$blank);
function information ($search,$id,$blank,$category,$recent,$comment,$subscribe,$pages,$pending,$profile,$deleted,$reported) {
//code
}
You could pass in an array with the specified keys, and merge it with an array of default values
So instead of
function foo($arg1 = 3, $arg2 = 5, $arg3 = 7) { }
You'd have
function foo($args) {
$defaults = array(
'arg1' => '',
'arg2' => null,
'arg3' => 7
);
// merge passed in array with defaults
$args = array_merge($defaults, $args);
// set variables within local scope
foreach($args as $key => $arg) {
// this is to make sure that only intended arguments are passed
if(isset($defaults[$key])) ${$key} = $arg;
}
// rest of your code
}
Then call it as
foo(array('arg3' => 2));
Yes, pass an array instead, or refactor. A long arguments list is usually a bad smell.
function information(array $params) {....
information(array('search'=>'.....
Twelve arguments are generally too many for one function. It's likely that your code could be simplified (including the argument lists getting shorter) by refactoring function information which looks likely to be a monster.
Stopgap measures you can use in the meantime are
adding default argument values
making the function accept all its arguments as an array
Both of the above will require you to visit all call sites for the function for review and modification.
Adding default arguments is IMHO the poor choice here, as by looking at the example call it seems that you would need to make all arguments default, which in turn means that the compiler will never warn you if you call the function wrongly by mistake.
Converting to an array is more work, but it forces you to rewrite the calls in a way that's not as amenable to accidental errors. The function signature would change to
function information(array $params)
or possibly
function information(array $params = array())
if you want all parameters to be optional. You can supply defaults for the parameters with
function information(array $params) {
$defaults = array('foo' => 'bar', /* ... */);
$params += $defaults; // adds missing values that have defaults to $params;
// does not overwrite existing values
To avoid having to rewrite the function body, you can then use export to pull out these values from the array into the local scope:
export($params); // creates local vars
echo $foo; // will print "bar" unless you have given another value
See all of this in action.
You can make it so the function wil automatically fill the variable with a given value like an empty string:
function information ($subscribe, $search="", $id="", $blank="", $category="", $recent="", $comment="", $pages="", $pending="", $profile="", $deleted="", $reported="") {
//code
}
Yes, there are several ways:
Accept an associative array as a single argument, and pass what you need to that. Throw exceptions if a critical argument is missing.
Place critical arguments at the head of the function definition, and optional ones at the end. Give them a default value so that you don't have to declare them.
Recosinder your function. 12 arguments is much too many for one function. Consider using a class/object, or dividing the work between different functions.
Several ways:
function test($input = "some default value") {
return $input; // returns "some default value"
}
function test($input) {
return $input;
}
test(NULL); // returns NULL
function test() {
foreach(func_get_args() as $arg) {
echo $arg;
}
}
test("one", "two", "three"); // echos: onetwothree
In the following example, is it possible to access the 'str' value from within the anonymous function?
$foo = array(
'str' => 'THIS IS A STRING',
'fn' => function () {
// is it possible from within here to access 'str'?
}
);
if $foo is defined in the global namespace you should be able to access it via $GLOBALS['foo']['str'] (or make it available via the global $foo; construct). If it isn't (local var, parameter, member variable, …), you have to pass it (as reference!) to the anonymous function:
$foo = array(
'str' => 'THIS IS A STRING',
'fn' => function () use(&$foo) {
echo $foo['str'];
}
);
I have found a different way to do this without using global variables:
<?php
$arr = array("a" => 12,
"b" => function($num)
{
$c = $num * 2;
return $c;
});
echo $arr["b"]($arr["a"]);
?>
Note the weird syntax of ending the array index call with method parentheses. By passing $arr["a"] as a parameter you can have access to that value (I imagine you could pass by reference as well).If you were not to pass anything into the anonymous function, you would call it like this:
$arr["b"]();
If you don't include the method parentheses it won't work.