【问题标题】:how to return a status from functions in php如何从php中的函数返回状态
【发布时间】:2014-02-11 07:40:19
【问题描述】:

我是 OOPHP 的新手。现在我正在编写一个搜索算法来搜索文件夹和子文件夹中的文件名。现在工作正常。但是在搜索后,如果文件名存在,它应该显示结果,如果不存在,它应该抛出一条消息,如“找不到文件”。为了实现这个功能,我尝试了在调用函数时以不同的方式更新状态变量。但是变量的范围没有传入全局。请查找以下代码以供参考(我在这里删除了状态变量以避免混淆)。让我知道如何通过更改代码来实现这一点..

    function recursiveGlob($dir, $ext) 
    {
        $strsear=$_POST["stringsearch"];

        $globFiles = glob("$dir".DIRECTORY_SEPARATOR."$strsear*.$ext");
        $globDirs  = glob("$dir/*", GLOB_ONLYDIR);

        foreach ($globDirs as $dir) 
        {
           recursiveGlob($dir, $ext);

        }

        foreach ($globFiles as $file) 
        {
            print "$file";      
        }
     }

【问题讨论】:

标签: php


【解决方案1】:
   function recursiveGlob($dir, $ext) 
{
    $strsear=$_POST["stringsearch"];

    $globFiles = glob("$dir".DIRECTORY_SEPARATOR."$strsear*.$ext");
    $globDirs  = glob("$dir/*", GLOB_ONLYDIR);

    foreach ($globDirs as $dir) 
    {
       recursiveGlob($dir, $ext);

    }

    foreach ($globFiles as $file) 
    {
        return $file;      
    }
 }



     $string=recursiveGlob($dir, $ext) 
     if(empty($string))s
     print "File Not Found";
     else
     print "File Found".$string;

小改动:

foreach ($globFiles as $file=>$v) {

 print "$v"; 
return $v; 

}

}

 if(!empty($v))
 print "File Found";
 else
 print "File Not Found";

【讨论】:

    【解决方案2】:
    function recursiveGlob($dir, $ext) {
    $strsear=$_POST["stringsearch"];
    $globFiles = glob("$dir".DIRECTORY_SEPARATOR."$strsear*.$ext");
    $globDirs  = glob("$dir/*", GLOB_ONLYDIR);
    foreach ($globDirs as $dir) {
        recursiveGlob($dir, $ext);
    }
    foreach ($globFiles as $file=>$v) {
         echo $v;
        if(count($v)!=0)$status=1;
    }
     $GLOBALS['status']=$status;}
    

    【讨论】:

    • 最后我们可以用 if(is_null($status)){ echo "Sorry. No match found."; }
    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多