且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP中的全局变量

更新时间:2023-02-04 08:57:11

您需要在函数本身内部声明$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.