Assigning a variable when calling a function

I inherited a php code base that contains some variable assignments in function calls:

<?php function some_func($foo, $state) { .... } some_func("random stuff", $state = true); ... some_func("other stuff", $state = false); ... ?> 

I did some research and some tests, but I can’t find out what is defined for this code in PHP.

How is the value of the second argument some_func() calculated? The contents of the 4state variable (true on first call, false for a second)? Or is it the result of the assignment (i.e., the assignment of true / false to the $state variable was successful, so some_func got true ?

What is the value of the $state variable in the global scope? The result of the assignment, i.e. True after the first call, false after the second?

+7
variable-assignment php
source share
2 answers

I also had to work with a codebase that had function calls like this. Fortunately, I had access to the developers who wrote the code. Here is what I learned.

Scenario 1:

Just a way to document the code. You know the name of the variable that you pass to the function.

Scenario 2:

Here is the link: http://www.php.net/manual/en/language.references.pass.php If you see, they specifically call your case:

 foo($a = 5); // Expression, not variable 

A 'dummy' pass-by-ref. Depending on your version of PHP, this may cause a warning. I got this: Strict Standards: Only variables should be passed by reference in ...

Now let me tell you in detail about what is happening in this situation.

The danger is that your example you provided does not display "gotcha!". behavior. In this case, your $arg2 , which you echo away from the function, will always be what it is in the function call. In addition, the called function will also be sent a β€œcopy” of this value and will work with it. I say "copy" because, although the function requires omissions, it actually gets a copy, similar to what the normal parameter of the function will receive.

If you change $arg2 , which is inside the function, it WILL NOT change $arg2 , which is outside the function, as you would expect from a function that passes through -REF.

+5
source share

To assign a variable during a function call, you must pass it as a reference ( &$var ):

 function my_function($arg1, &$arg2) { if ($arg1 == true) { $arg2 = true; } } my_function(true, $arg2 = false); echo $arg2; 

outputs 1 (true)

 my_function(false, $arg2 = false); echo $arg2; 

outputs 0 (false)

How is the value of the second argument calculated for some_func ()?

It is not "calculated", but explicitly sets: $state = true / false , and then passed as an argument to some_func() .

What is the value of the $ state variable in the global scope?

$state does not exist in the global realm.

+1
source share

All Articles