【问题标题】:PHP scope issues in loops循环中的 PHP 范围问题
【发布时间】:2015-01-24 09:49:28
【问题描述】:

我尝试搜索,但不知道为什么会失败。

    public function slim_items( $faties ) {

    $smallies = array ();
    global $faties;

    require_once 'wp-content/plugins/cl-rest/modules/CLBasicItem.php';
    require_once 'wp-content/plugins/cl-rest/helpers.php';

    foreach ($faties as $fat){
        $smallies[]=new CLBasicListItem($fat);
    }

    return $smallies;

}

这个函数是一个类的一部分。问题是一旦 foreach(我尝试过一个简单的 for)循环开始运行,$fat 就会变为 null。一旦进入循环范围,它就不会引用 $faties。

请问我在这里做错了什么? $faties 真的必须被声明为全局变量吗?我注意到您甚至不能将它们声明为全局类字段。

如果有人可以帮助推荐除 Eclipse for PHP 之外的开源 IDE,我将不胜感激。也许我做错了,但我发现像单步执行代码和设置断点这样的简单任务是相当痛苦的。我遇到的所有异常方式,IDE/堆栈几乎没有显示实际原因或完全错过了问题。事实上,PHP/Apache 在发生错误时默认发送的消息通常比 eclipse 提供的捕获异常的奇怪时间有用得多。

编辑:下面回答得更好,但我可以发誓我尝试了代码,但没有将 $faties 声明为全局(甚至根本没有)并且它没有工作。我被更多的惊慌失措了

public function slim_items( $faties ) {

    global $uglies, $smallies;
    $uglies=$faties;
    $smallies = array ();

    require_once 'wp-content/plugins/cl-rest/modules/CLBasicItem.php';
    require_once 'wp-content/plugins/cl-rest/helpers.php';

    foreach ($uglies as $fat){
        $smallies[]=new CLBasicListItem($fat);
    }

    return $smallies;

}

直到现在都无法返回这里查看。谢谢大家,因为您的解决方案显然更好

【问题讨论】:

  • var_dump($faties);
  • 你重新声明 $faties, global $faties; 覆盖参数。只需删除此字符串。

标签: php loops scope


【解决方案1】:

注意 public function slim_items( $faties ) {global $faties; 您将 $fatties 重新声明为
全球。

【讨论】:

    【解决方案2】:

    这行得通吗?

    public function slim_items( $faties ) {
    
        $smallies = array ();
        // global $faties; <-- this is already declared
    
        require_once 'wp-content/plugins/cl-rest/modules/CLBasicItem.php';
        require_once 'wp-content/plugins/cl-rest/helpers.php';
    
        foreach ($faties as $fat){
            $smallies[]=new CLBasicListItem($fat);
        }
    
        return $smallies;
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 2011-09-16
      • 2012-02-16
      相关资源
      最近更新 更多