PHP 静态变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1642333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Static Variables
提问by omg
$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 right,but I need a better explanation?
我猜它输出 5 0 1 是对的,但我需要更好的解释?
回答by soulmerge
The variable $countin the function is not related in any kind to the global $countvariable. The statickeywordis 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函数中的变量与全局$count变量没有任何关系。该static关键字与 C 或 Java 中的相同,表示:仅初始化此变量一次,并在函数结束时保持其状态。这意味着,当执行重新进入函数时,它看到内部 $count 已经被初始化并存储为最后一次1,并使用该值。
回答by Alix Axel
$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.
我希望这能让你清醒。
回答by Thorarin
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.
您有两个单独的变量,它们都称为 $count,但它们的作用域不同。第一个变量没有显式声明,但在你第一次赋值时就存在了。
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.
第二个变量(在方法内部)仅对该方法可见。由于它是static,它的值在同一方法的多次执行之间保留。分配$count = 0;仅在第一次运行该方法时执行。
As for the increment operator (++), the result of the evaluation is the value beforeit 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.
对于自增运算符 (++),求值的结果是自增之前的值,因为(一元)运算符在变量名之后。所以是的,输出将是 5, 0, 1。
如果你要写return ++$count;,结果将是 5, 1, 2。
Note: the ++$countyou have in your existing code, it is effectively equivalent to $count++, since the result of the evaluation is discarded. The effect to the $countvariable is the same: it gets incremented by 1.
注意:++$count您现有代码中的 ,它实际上等效于$count++,因为评估结果被丢弃。对$count变量的影响是相同的:它增加 1。
回答by Fenton
First echo: Gives you the variable $count that you declare in your first line.
第一个回声:为您提供您在第一行中声明的变量 $count。
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.
第二个回声:调用 get_count ,它创建静态变量 $count (因此它在此函数的上下文中)并且当您实例化静态变量时,您将其设置为零。return $count++ 是我们在代码中通常避免的那些行之一 - 但本质上,它在返回值后递增。
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.
第三个回声:同样,在上一次调用 get_count 之后,0 增加到 1,这里发生同样的情况——它返回 1 并将值增加到 2。
Does that help or is that actually more confusing?
这有帮助还是实际上更令人困惑?
回答by Alex Myznikov
PHP has a well known statickeyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that staticmay also be used inside functions to define static variables.
PHP 有一个众所周知的static关键字,它在面向对象的 PHP 中广泛用于定义静态方法和属性,但应该记住,它static也可以在函数内部使用来定义静态变量。
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 $counterwithout staticthen each time the echoed value would be the same as $numparameter passed to the function. Using staticallows to build this simple counter without an additional workaround.
如果我们$counter没有定义,static那么每次回显的值将与$num传递给函数的参数相同。使用static允许构建这个简单的计数器,而无需额外的解决方法。
Static variables use-cases
静态变量用例
- To store values between consequent calls to function.
- To store values between recursive calls when there is no way (or no purpose) to pass them as params.
- 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.)
自 PHP 5.6 起,静态变量只能定义为标量或标量表达式。为其分配其他值不可避免地会导致失败(至少在撰写本文时如此)。
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.
在函数调用之间保持值的另一种方法是使用闭包。闭包是在 PHP 5.3 中引入的。简而言之,它们允许您将函数范围内的某些变量集的访问限制为另一个匿名函数,这将是访问它们的唯一方法。在闭包变量中可能会模仿(或多或少成功)OOP 概念,如结构化编程中的“类常量”(如果它们在闭包中通过值传递)或“私有属性”(如果通过引用传递)。
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.
后者实际上允许使用闭包而不是静态变量。使用什么总是由开发人员决定,但应该提到静态变量在处理递归时绝对有用,值得开发人员注意。
回答by Maximilian Mayerl
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.
嗯,首先,函数内部的 $count 和函数外部的 $count 是两个不同的变量。这解释了为什么第一个输出打印 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.
因此,当您第一次调用 get_count() 时,变量被设置为 0,然后返回。返回后,变量递增。
When you call the function for the second time, the variable is still 1. This value is returned and then incremented to 2.
当您第二次调用该函数时,该变量仍为 1。该值被返回,然后递增为 2。

