【问题标题】:Laravel undefined functionLaravel 未定义函数
【发布时间】:2016-03-15 15:08:12
【问题描述】:

我有以下功能:

# Get Directories of Path as Array
function dirToArray($dir) {

   $result = array();

   $cdir = scandir($dir);
   foreach ($cdir as $key => $value)
   {
      if (!in_array($value,array(".","..")))
      {
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
         {
            $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
         }
         else
         {
            $result[] = $value;
         }
      }
   }

   return $result;
}

然后这样称呼它:

        $watchFolder = 'C:\\xampp\\htdocs\\project\\One\\';
        $this->dirToArray($watchFolder);

但我收到以下错误:

调用未定义函数 App\Http\Controllers\dirToArray()

有人知道怎么解决吗?

编辑: 所以我的完整控制器看起来像这样:

<?php

namespace App\Http\Controllers;

use DB;
use Mail;
use File;
use Input;
use Request;
use Illuminate\Filesystem\Filesystem;
use App\Http\Controllers\Controller;

class ProductRController extends Controller
{

    public function createProduct()
    {
            ...
            $watchFolder = 'C:\\xampp\\htdocs\\Product\\R\\';
            $this->dirToArray($watchFolder);

            return redirect()->route('root')->with('message', 'Success')->withInput();
        }
        else
        {
            return redirect()->route('newProduct')->with('message', 'Error')->withInput();
        }

    }

    # Get Directories of Path as Array
    function dirToArray($dir) {

       $result = array();

       $cdir = scandir($dir);
       foreach ($cdir as $key => $value)
       {
          if (!in_array($value,array(".","..")))
          {
             if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
             {
                $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
             }
             else
             {
                $result[] = $value;
             }
          }
       }

       return $result;
    }

}

【问题讨论】:

  • 你把你的函数放在哪里了?
  • 我把它放在控制器里面
  • 你在哪里叫它?在这里工作/不工作级别也无关紧要,但是将方法显式声明为public 是最佳实践(和 PHP 标准)
  • 你能用相应的文件名更新你的问题吗?
  • 尝试使用$result[$value] = $this-&gt;dirToArray($dir . DIRECTORY_SEPARATOR . $value);

标签: php arrays function laravel undefined


【解决方案1】:

您仍然需要在函数内使用 $this-&gt;,就像在函数外使用它一样,因为 $this 表示您正在调用您的方法的对象:

$result[$value] = $this->dirToArray($dir . DIRECTORY_SEPARATOR . $value);

【讨论】:

  • 谢谢,抱歉没有找时间和名字
  • 不鼓励仅使用代码回答。如果这将被选为“最佳答案”,请使用有关问题发生原因以及解决问题的方法的信息进行更新。如果此答案更新,我可以删除我的答案。
  • @patricus,我已经发表评论,回答 before 你(相差 2 分钟)。然后我将我的回答从评论复制粘贴到答案。看看我评论的时间戳。你是想说“cmets 不算数”之类的吗?
  • @AlexeyMezenin 我看到了这个问题并写了一个答案。这样做时我不会不断刷新 cmets。我不关心“获得复选标记”,但我确实关心复选标记反映了“最佳答案”。截至目前,这不是最好的答案,因为它没有解释任何东西。这个站点应该不仅仅是一个额外的调试器。请更新此答案以解释问题以及为什么会解决此问题,以便我可以删除我的答案。
  • @patricus,我认为答案很明显,OP知道使用$this(看看他的代码,他在函数外使用$this),他只是忘记再次使用它函数内部。这很奇怪,但是好的,我已经更新了我的帖子,所以你可以开心。
猜你喜欢
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 2018-01-08
  • 2016-10-03
  • 2023-03-21
  • 2018-02-05
  • 2016-03-30
  • 2015-04-28
相关资源
最近更新 更多