开发者

PHP Static Variables

开发者 https://www.devze.com 2022-12-09 22:26 出处:网络
$count = 5; function get_count() { static $count = 0; return $count++; } echo $count; ++$count; echo get_count();
$count = 5;
function get_count()
{
    static $count = 0;
    return $count++;
}
echo $count;
++$count;
echo get_count();
echo get_count();

I guessed it outputs 5 0 1 and it's r开发者_如何学运维ight,but I need a better explanation?


The variable $count in the function is not related in any kind to the global $count variable. The static keyword is the same as in C or Java, it means: Initialize this variable only once and keep its state when the function ends. This means, when execution re-enters the function, it sees that the inner $count has already been initialized and stored the last time as 1, and uses that value.


$count = 5; // "outer" count = 5

function get_count()
{
    static $count = 0; // "inner" count = 0 only the first run
    return $count++; // "inner" count + 1
}

echo $count; // "outer" count is still 5 
++$count; // "outer" count is now 6 (but you never echoed it)

echo get_count(); // "inner" count is now + 1 = 1 (0 before the echo)
echo get_count(); // "inner" count is now + 1 = 2 (1 before the echo)
echo get_count(); // "inner" count is now + 1 = 3 (2 before the echo)

I hope this clears your mind.


You have two separate variables that are both called $count, but they have a different scope. The first variable is not explicitly declared, but comes into existence when you first assign it.

The second variable (inside the method) is only visible to that method. Since it's static, its value is retained between multiple executions of the same method. The assignment $count = 0; is only executed the first time the method is run.

As for the increment operator (++), the result of the evaluation is the value before it was incremented, because the (unary) operator comes after the variable name. So yes, the output would be 5, 0, 1.
If you were to write return ++$count;, the result would have been 5, 1, 2.

Note: the ++$count you have in your existing code, it is effectively equivalent to $count++, since the result of the evaluation is discarded. The effect to the $count variable is the same: it gets incremented by 1.


First echo: Gives you the variable $count that you declare in your first line.

Second echo: calles get_count which creates the static variable $count (so it's in context for this function) and when you instantiate the static variable you're setting it to zero. return $count++ is one of those lines we usually avoid in code - but essentially, it is incremented AFTER the value is returned.

Third echo: Likewise, 0 was incremented to 1 after the previous call to get_count, the same happens here - it returns 1 and increments the value to 2.

Does that help or is that actually more confusing?


PHP has a well known static keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that static may also be used inside functions to define static variables.

What is a 'static variable'?

A static variable differs from an ordinary variable defined in function's scope in that it does not loose its value when program execution leaves this scope. Let's consider the following example of using static variables:

function countSheep($num) {
   static $counter = 0;
   $counter += $num;
   echo "$counter sheep jumped over fence";
}

countSheep(1);
countSheep(2);
countSheep(3);

Result:

1 sheep jumped over fence
3 sheep jumped over fence
6 sheep jumped over fence

If we'd defined $counter without static then each time the echoed value would be the same as $num parameter passed to the function. Using static allows to build this simple counter without an additional workaround.

Static variables use-cases

  1. To store values between consequent calls to function.
  2. To store values between recursive calls when there is no way (or no purpose) to pass them as params.
  3. To cache value which is normally better to retrieve once. For example, result of reading immutable file on server.

Tricks

A static variable exists only in a local function scope. It can not be accessed outside of the function it has been defined in. So you can be sure that it will keep its value unchanged until the next call to that function.

Since PHP 5.6, a static variable may only be defined as a scalar or as a scalar expression. Assigning other values to it inevitably leads to a failure (at least at the moment this article was written.)

Nevertheless you are able to do so just on the next line of your code:

function countSheep($num) {
    static $counter = 0;
    $counter += sqrt($num);//imagine we need to take root of our sheep each time
    echo "$counter sheep jumped over fence";
}

Result:

2 sheep jumped over fence
5 sheep jumped over fence
9 sheep jumped over fence

A static function is kinda 'shared' between methods of objects of the same class. It is easy to understand by viewing the following example:

class SomeClass {
    public function foo() {
        static $x = 0;
        echo ++$x;
    }
}

$object1 = new SomeClass;
$object2 = new SomeClass;

$object1->foo(); // 1
$object2->foo(); // 2 oops, $object2 uses the same static $x as $object1
$object1->foo(); // 3 now $object1 increments $x
$object2->foo(); // 4 and now his twin brother

This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.

Is static variable the only way to keep values between calls to a function?

Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.

The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.


Well, first of all, $count inside the function and $count outside of the function are 2 different variables. That explains why the first output prints 5.

Now for the static: Static means your local variable is created only once, when the function executes for the first time. Every function execution afterwards uses the same variable, so the latest values of the variable in the last function execution is still there.

So, when you first call get_count(), the variable is set to 0 and then returned. After the return, the variable is incremented.

When you call the function for the second time, the variable is still 1. This value is returned and then incremented to 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号