【问题标题】:Function returns strings but not when stored in variable函数返回字符串,但存储在变量中时不返回
【发布时间】:2015-10-18 10:22:52
【问题描述】:

我写的一个函数有一个奇怪的问题。当返回像“Hello”这样的硬编码字符串时,它会返回这个值,但是当我将此值存储在变量中时,它不会返回任何内容。

此外,当我不将它存储在变量中并尝试返回它时,什么都不会返回。

下面是我的代码。谁能看到我做错了什么?

提前致谢。

 public function getPath($pageID = null) {
    if($pageID == null) $pageID = $this->id;

    $data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");

    if(!empty($data)) {
        $this->tempPath[] = $data['basename'];

        if($data['parentID'] != 0) {
            $this->getPath($data['parentID']);
        } else {
            $returnPath = $this->tempPath;
            $this->tempPath = array();
            $returnPath = implode('/', array_reverse($returnPath));
            //This variable holds the value, when echo'ed its the correct value
            echo $returnPath;

            return $returnPath;
        }
    }
}

【问题讨论】:

  • 无法重现您的问题。你有任何错误吗?你给我们看你的真实代码吗?
  • 这是函数中使用的所有代码,它产生了正确的数据,但返回时没有返回任何内容。当我编码时:返回“Hello”它确实返回“Hello”,但它不返回变量中的任何值。
  • 在 return 语句之前var_dump($returnPath); 的确切输出是什么?
  • 这是输出: string(15) "admin/dashboard" string(15) "admin/pages/add" string(11) "admin/pages"
  • 这段代码是不是在循环中,你没有向我们展示?!

标签: php string function oop


【解决方案1】:

将代码重写为以下内容,现在可以正常工作了

 public function getPath($pageID = null) {
    if($pageID == null) $pageID = $this->id;

    $data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");

    if(!empty($data)) {
        $this->tempPath[] = $data['basename'];
    }

    return implode('/', $this->tempPath);
}

问题是代码处于 foreach 循环中,该循环不断覆盖正确的值并循环直到没有返回路径。感谢您的建议。

更多的代码并不总是更好:-)

【讨论】:

    猜你喜欢
    • 2016-03-28
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    相关资源
    最近更新 更多