PHP中的全局变量 [英] Global variables in PHP
问题描述
我正在编写一个脚本,它将多次从输入文件中的单词中选择一个随机单词.现在多次调用file()
似乎效率低下,因此我正在考虑为文件中的单词创建一个全局数组,以及一个将文件加载到数组中的函数(在选择随机单词之前调用).为什么不起作用?
I'm writing a script that will select a random word from among words in an input file, multiple times. Now calling file()
multiple times seems inefficient, so I'm thinking of having a global array for the words from the file and a function that will load the file into the array (called before selecting random words). Why doesn't it work?
global $words;
function init_words($file)
{
$words = file($file);
$count = count($words);
echo "$count words<br>\n"; // "3 words"
}
init_words("/foo/bar");
$count = count($words);
echo "$count words<br>\n"; // "0 words"
推荐答案
您需要在函数本身内部声明$words
全局变量.参见:
You need to declare $words
global within the function itself. See:
$words = '';
function init_words($file)
{
global $words;
$words = file($file);
$count = count($words);
echo "$count words<br>\n"; // "3 words"
}
我建议您阅读PHP手册中的可变范围一章
I suggest you review the variable scope chapter in the PHP manual.
顺便说一句,我永远不会以这种方式编写这段代码.除非绝对必要,否则请避免使用全局变量.
As an aside I would never write this code in this way. Avoid globals unless they are absolutely necessary.
我将以这种方式编写您的代码来避免此问题:
I would write your code this way to avoid this problem:
function init_words($file)
{
$words = file($file);
$count = count($words);
echo "$count words<br>\n"; // "3 words"
return $words;
}
$words = init_words("/foo/bar");
$count = count($words);
echo "$count words<br>\n"; // "3 words"
请参阅PHP手册中的返回值章节有关更多信息.
Please see the returning values chapter in the PHP manual for more information on this.
这篇关于PHP中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!