These function statements are confusing me.
I'm new to php, help me to understand these functions:
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
first echo outputs 10
Second echo outputs 16
What is the difference between these 2 functions?
There are two types of call:
1) Call by value: addFive($num)
2) Call by reference: addSix(&$num)
In first case, you are just passing value of the variable.
Hence, only value gets modified keeping original variable untouched.
In second case, you are passing reference to the variable, hence the original value gets modified.
The first function passes the argument by value - in other words, it's copied into the function, and any change you perform on it will be on the local copy.
The second function passes the argument by reference (note the & before it in the function's signature). This means the variable itself is passed, and any modification you perform on it will survive beyond the function's scope.
& is used to pass address of an variable in second function declaration "addSix(&$num) {}"
In second function while calling addSix( $orignum ); updation of value is done on address of "$orignum"
whereas in first function updation is done on "$num"
First function add 5 to your number and second adds 6 to your number
$num+=6 means $num= $num+6
And first function works on Call by value and second function works on Call by reference
Related
I have this code.
$add = (function () {
$counter = 0;
return function () use(&$counter) {return $counter += 1;};
})();
echo $add(); //1
echo $add(); //2
echo $add(); //3
Expected Output:
111
Original Output:
123
Inside the function $counter=0 is assigned by 0 so the &$counter should be 0.
So when i called it second time it sees $counter=0 and so that &$counter will be 0, Isn't it?
Why it is incrementing?
It does not call $counter=0 for the second time. You call it just once when initiating the first function. When you call $add(), you call every time the second function (that is in your return statement) which just uses the modified value of $counter that you passed by reference. If you would add echo $counter; after the $counter = 0; you will see that.
What do you mean by "sees"? The first time you execute $add(), the inner counter is counted up. As you used a reference pointer (through adding the ampersand in use(&$counter)) to the original $counter, this is also manipulated, so after executing this once, the counter variable no longer contains a zero.
When you remove that ampersand, the innermost function uses a fresh counter each and every time, such that your expected output is met
Because you pass a reference to the function the initial $counter = 0; value is also increased each time you add 1 to it using $counter += 1; that's why your result is "123".
To get "111" you need to pass a variable to a function $counter, not a reference.
i'm just confused about assigning variable values on php to another one , how does it work?!
for Example:
<?PHP
$var1=mysqli_fetch_array($query);
while($var2=$var1)
{
echo $var2[$key]; /** this wont't work Correctly however $var1 it's
value = to mysqli_fetch_array**/
}
while($var1=mysqli_fetch_array($query))
{
echo $var1[$key]; /** this will work , why ! **/
}
?>
A peculiarity in PHP's assignment behaviour, is that it also returns the result of the assigned value. This allows for statements such as:
$a = $b = $c = 3; // All of a, b and c will equal 3
And:
while ($variable = call_a_function()) {
do_something_with($variable);
}
In the latter example, variable gets assigned to the output of call_a_function() at the beginning of the loop iteration; as soon as call_a_function() returns a value that evaluates to false, the loop ends. If the returned value does not evaluate to false, variable will contain whatever value was returned, until it gets overwritten again.
Your examples use a similar behaviour. The crucial difference between
$var1=mysqli_fetch_array($query);
while($var2=$var1)
{
echo $var2[$key];
}
And:
while($var1=mysqli_fetch_array($query))
{
echo $var1[$key];
}
...is that in the first example, $var1 is only assigned to the return value of mysqli_fetch_array($query) before the loop starts, while in the second example, $var1 is assigned to the return value of mysqli_fetch_array($query) in every iteration of the loop.
What makes the two pieces of code crucially different, in the end, is the fact that mysqli_fetch_array($query) returns different results, depending on circumstances.
Combining the code snippets into an example that works as intended, yet uses $var2, yields:
while($var2=$var1=mysqli_fetch_array($query))
{
echo $var2[$key];
}
or
$var1=mysqli_fetch_array($query); // ask first time
while($var2=$var1)
{
echo $var2[$key];
$var1=mysqli_fetch_array($query); // ask again, because the answer changed
}
TL;DR: The first example asks a question once, the second asks a question many times. In this case, the intended behaviour of your code requires the question to be asked multiple times, because the answer changes over time.
We got a PHP file in school with some functions and one of them is the following:
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
My question: What does the $afields=null and $avalues=null mean?
Thank you!
function serviceRec($db,$table,$afields=null,$avalues=null){ .... }
It means that, when you call your function and don't pass those parameters then it'll by default place value as null
Example :
function hello($name = "anonymous"){
return "Hello $name \n";
}
echo hello();//Hello anonymous
echo hello("BigSeeProduction");//Hello BigSeeProduction
DOCS
These assignments are default values. If you were to call the function as e.g.
serviceRec($a, $b)
the omitted parameters would be assumed to be null. If, on the other hand, you called the function as e.g.
serviceRec($a, $b, $c, $d)
$afields would be set to $c and $avalues to $d.
Of course, you could also call with 3 parameters.
It Means it's the default value. So when u don't fill this parameter it will be set as null.
See the man here :
PHP.net : default value function
That indicates, that if you leave that parameter out(Don't specify it at all), the value after the =, in this case null is used. So if you don't care about these parameters just leave them out. It has the same effect as just supllying null.
Is there any way in PHP to know where a variable was initialized or assigned the value for first time OR where it was last modified?
I think it should be possible to know this because PHP gives some such hint in errors. Like: Can not redeclare abc() (previously declared in /path/to/file.php)
EDIT:
I need this because:
function abc() {
global $page; //this should be int.
if($page == 2) { ... }
}
But when this function is run; I get error Can not convert object into int. This is because some where in my code $page is overriden by any object. I need to find that place where it was modified. Or I'll have to dig through entire code.
You can find out which object is being assigned to your $page variable using the native php function get_class() :
get_class($page);
You would normally want to debug this using a unit test where you would test that the variable $page is numeric.
If you just want to debug on-screen try:
if(is_object($page)){
die(get_class($page));
}
or via an exception:
if(is_object($page)){
throw new Exception('$page must be numeric object given of type : '.get_class($page));
}
This will help you find which object is being assigned to your variable and just point you in the right direction.
If you want to know where a variable was defined then you are out of luck; there is no way to find that out, other than actually looking through your code and finding it.
Your problem seems to be that you are allowing a variable into a function (using global). Because the variable is defined outside the function it can be modified at any time. If you want to always know what the variable contains then you should pass it as an argument instead:
$page = 2;
function abc($page) {
if($page == 2) { ... }
}
$test = abc($page);
If you want to make sure that the value of the variable is a number then you can find that out by simply validating the argument (or the global variable, for that matter):
if (is_int($page) or ctype_digit($page)) {
echo 'The $page variable is a number';
} else {
echo 'The $page variable is NOT a number';
}
I'm 'dissecting' PunBB, and one of its functions checks the structure of BBCode tags and fix simple mistakes where possible:
function preparse_tags($text, &$errors, $is_signature = false)
What does the & in front of the $error variable mean?
It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.
function passByReference(&$test) {
$test = "Changed!";
}
function passByValue($test) {
$test = "a change here will not affect the original variable";
}
$test = 'Unchanged';
echo $test . PHP_EOL;
passByValue($test);
echo $test . PHP_EOL;
passByReference($test);
echo $test . PHP_EOL;
Output:
Unchanged
Unchanged
Changed!
It does pass by reference rather than pass by value.
This allows for the function to change variables outside of its own scope, in the scope of the calling function.
For instance:
function addOne( &$val ) {
$val++;
}
$a = 1;
addOne($a);
echo $a; // Will echo '2'.
In the case of the preparse_tags function, it allows the function to return the parsed tags, but allow the calling parent to get any errors without having to check the format/type of the returned value.
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $errors = "Error!") will affect the variable passed by the calling function.
It means that the variable passed in the errors position will be modified by the called function. See this for a detailed look.