0
我正在用php构建一个图片库。我使用的代码是这样的:PHP变量的范围
function ImageBlock() {
$dir = 'img-gallery';
$images = scandir($dir);
$classN = 1;
foreach ($images as $image) {
if ($image != '.' && $image != '..') {
echo '<img class="image' . $classN . '" src="img-gallery/' . $image . '" width="300px"
height="300px">';
}
$classN++;
}
}
如果我在另一个文件中调用此函数它的工作。我的问题是,如果我使用下面的COSE,宣告了函数的变量...它不工作了:
$dir = 'img-gallery';
$images = scandir($dir);
function ImageBlock() {
$classN = 1;
foreach ($images as $image) {
if ($image != '.' && $image != '..') {
echo '<img class="image' . $classN . '" src="img-gallery/' . $image . '" width="300px"
height="300px">';
}
$classN++;
}
}
为什么,我的意思是外部声明的变量应该有一个全球范围内,据我所知,和应该从功能内部访问。不是吗?
这种情况下有一个['global'](http://php.net/global)的关键字。 – BlitZ
http://php.net/manual/zh/language.variables.scope.php – user4035