函数内的`static`关键字? [英] `static` keyword inside function?
本文介绍了函数内的`static`关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在查看 Drupal 7 的源代码,发现了一些我以前从未见过的东西.我在php手册中做了一些初步查找,但没有解释这些示例.
I was looking at the source for Drupal 7, and I found some things I hadn't seen before. I did some initial looking in the php manual, but it didn't explain these examples.
关键字static
对函数内的变量有什么作用?
What does the keyword static
do to a variable inside a function?
function module_load_all($bootstrap = FALSE) {
static $has_run = FALSE
推荐答案
它使函数在多次调用之间记住给定变量的值(在您的示例中为$has_run
).
It makes the function remember the value of the given variable ($has_run
in your example) between multiple calls.
您可以将其用于不同的目的,例如:
You could use this for different purposes, for example:
function doStuff() {
static $cache = null;
if ($cache === null) {
$cache = '%heavy database stuff or something%';
}
// code using $cache
}
在这个例子中,if
只会被执行一次.即使多次调用 doStuff
也会发生.
In this example, the if
would only be executed once. Even if multiple calls to doStuff
would occur.
这篇关于函数内的`static`关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文