I have a question in my todays Exam in which I have to determine the output.
<?php
function statfun($x)
{
static $count=0;
$count += $x;
if ($count < 20) {
echo "$count <br>";
statfun(++$x);
} else {
echo "last num is $count";
}
}
statfun(2);
?>
The output is
2
5
9
14
last num is 20
I dont know why this is the output. I know it is due to the static member but each time it comes into the function the member $count is re-initialized.I had saw the documentation at Static Keyword.
But there is nothing written regarding the re-initialization of static variable? Can we re-initialize the static variable in PHP? With the same or any other value?
each time it comes into the function the member $count is re-initialized
This is incorrect. Static variables are initialized only once which is how statically declared variables differ from "ordinary" variables. So basically, you're assigning an initial value to $count. In multiple calls to statfun(), this static variable's value is preserved and can be reused.
From the manual, section "Using static variables":
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
Also look at the example-code in the manual. The difference stated there should answer your question.
when you pass 2 count is set to 2
with $count+=$x;
then you have called statfun(++$x) which is $x+1 and that is 2+1=3
so now $count will be $count+3 and that is 5, and then you call statfun with the value of 3 then $count will $count+(3+1) = 9 and so on and so on
static variable will hold its state. So if you call it like this
So basically static variable will hold its value and will not be re-initialized.
Related
I saw this on W3Schools.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
The output is 0, 1 and 2.
I wonder why it is not 0, 0 and 0.
Since each time the function is called, the variable x becomes 0 again.
I am a PHP beginner. Thanks!
If you declare a var static inside a function, the var keep it value over multiple calls. You could compare it to a static var inside of classes.
The code you post is a good example to see the actual effect. However I would only carefull use static inside functions, because most of the time, you need the static value somewhere else, reset the value, or something else which requires to much logic and makes the code really bad.
A good example would be a function, which returns a unique identifier for a given identifier. This could be simply achieved by using this code.
function unique_id($id) {
static $count = 0;
return $id . ($id++);
}
This example may clarify. static has a scope, thus is not a global variable. So I can define static $x outside the function and it will be defined there. Since static has scope, it wouldn't make any sense to keep on executing and resetting $x = 0. So, php will only acknowledge it the first time that line is called.
<?php
static $x = 1000;
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
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
I have such a function, and I declare the same static variable twice with different values. Then, I called the function, but the result surprised me.
function question(){
static $a=1;
$a++;
echo $a; // output:?
static $a=10;
$a++;
echo $a; // output:?
}
I thought the outputs would be: 2 11, but the outputs was: 11 12. Why?
If you declare and initialize the same static variable more than once inside a function, then the variable will take the value of the last declaration (static declarations are resolved in compile-time.)
In this case, the static variable of $a will take the value of 10 in the compile time, ignoring the value of 1 in the previous same declaration.
Static works the same way as it does in a class.
The variable is shared across all instances of a function.
so if you initialize same static variable many time then it will always take latest value.
A static variable exists only in the declared local function scope, but it does not lose its value when program execution leaves this scope.
The use of Static keyword is itself such that it will not lose track of the current count.
So In your case, function execution stops at $a = 10; $a++;
Hence you have 11 and 12 as output.
If you want output to be 2 and 11; keep only one declaration static like below.
function question(){
$a=1;
$a++;
echo $a; // output:?
static $a=10;
$a++;
echo $a; // output:?
}
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';
}
Edit: Made more clearer
I have a problem with a variable disappearing between function calls
firstly I start here with $pid being an int taken from a JSON string
print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($pid);
I get the output 'PID12' which is how it should be
Next in the Algorithm::getpredictionForPlayer
static function getpredictionForPlayer($pid)
{
print "PID2: ".$pid."\n";
$points =0;
for ($i = 0; $i < 10; $i++)
{
print "algorithm: ".$pid."\n";
$points += v4::predictPointsForPlayer($pid);
}
return intval($points/10);
}
Occasionally i get 'PID2: 12', but more often all that prints is 'PID2: '
Is there a reason the variable would disappear during this time?
Your variable in the global scope is $pid yet you are passing $player_id into the function
print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($player_id);
You've then got a parameter in your static method called $pid
static function getpredictionForPlayer($pid)
but this isn't the same as the variable in your global scope. In fact this will take the same value as the $player_id that you are passing in. If you want the $pid variable from your global scope to exist in the static method you should pass it in instead of $player_id.
btw, you should think about whether you really need a static method. Generally they make things hard to test and should be avoided if possible. Should you have a player object and call the method getPrediction() on that?
Change this line:
$a['points'] = Algorithm::getpredictionForPlayer($player_id);
To this:
$a['points'] = Algorithm::getpredictionForPlayer($pid);