【问题标题】:scope of variables in PHP [duplicate]PHP中的变量范围[重复]
【发布时间】:2013-09-27 13:43:46
【问题描述】:

我正在使用 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++;
    }
}

为什么,我的意思是在我所知的外部声明的变量应该具有全局范围,并且应该可以从函数内部访问。不是这样吗?

【问题讨论】:

标签: php variables global-variables scope global


【解决方案1】:

PHP 不是 JavaScript。全局命名空间中的函数在函数内部不可用,除非您明确地使它们如此。有三种方法可以做到这一点:

将它们作为参数传递(推荐)

function ImageBlock($images){

使用global关键字(强烈不推荐)

function ImageBlock(){
    global $images

使用$GLOBALS superglobal(强烈不推荐)

function ImageBlock(){
    $images = $GLOBALS['images'];

【讨论】:

  • 非常感谢。混乱消除了
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 2015-08-20
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多