2016-03-03 42 views
0

我有一个函数不能重新声明应用程序 funtion_name()

function getImg($img,$str,$input){ 
    // dd($img); 

    $img_path = public_path().'/images/photos/devices/'.$img.'.jpg'; 
    if(file_exists($img_path)){ 
     if(strpos($input,$str)){ 
      return $img; 
     }else{ 
      return 'no-img'; 
     } 
    }else{ 
     return 'no-img'; 
    } 
} 

然后,我这样称呼它

getImg('phone','phone',$input); 

为什么我不断收到这个错误?

不能重新声明应用程序\ GETIMG()


全功能

public static function img($input){ 

    $img_path = public_path().'/images/photos/devices/'; 
    $images = scandir($img_path, 1); 

    $devices = []; 
    foreach($images as $i=>$image){ 
     if($image != '.' && $image != '..' && $image != '.DS_Store'){ 
      $name = str_replace('.jpg', '', $image); 
      $devices[$i]['name'] = $name; 
     } 
    } 


    // dd($devices); 
    // dd($input); 


    foreach ($devices as $i=>$device) { 

     $matches = array_filter($devices, function($device) use ($input) { 
      return strpos($input, $device['name']) !== FALSE; 
     }); 

     if(count($matches) > 0){ 

      foreach ($matches as $match) { 

       $input = $match['name']; 

       $img_path = public_path().'/images/photos/devices/'.$input.'.jpg'; 
       if(file_exists($img_path)){ 
        return $input; 
       }else{ 
        return 'no-img'; 
       } 

      } 
     }else{ 

      // dd($input); 

      function getImg($img,$str,$input){ 
       // dd($img); 

       $img_path = public_path().'/images/photos/devices/'.$img.'.jpg'; 
       if(file_exists($img_path)){ 
        if(strpos($input,$str)){ 
         return $img; 
        }else{ 
         return 'no-img'; 
        } 
       }else{ 
        return 'no-img'; 
       } 
      } 

      getImg('phone','phone',$input); 
      getImg('ipad','ipad',$input); 
      getImg('iphone','iphone',$input); 
      // getImg('imac','imac'); 

     } 

    } 

} 

回答

1

你的函数应声明foreach循环之外,像这样

 function getImg($img,$str,$input){ 
      // dd($img); 

      $img_path = public_path().'/images/photos/devices/'.$img.'.jpg'; 
      if(file_exists($img_path)){ 
       if(strpos($input,$str)){ 
        return $img; 
       }else{ 
        return 'no-img'; 
       } 
      }else{ 
       return 'no-img'; 
      } 
     } 

     foreach ($devices as $i=>$device) { 
     .......... 
     } 
+0

唉好的。我知道了。谢谢。 – ihue

+0

如果有帮助,不要忘了标记答案已解决;) – PeterPan666

1

在PHP中一个func它始终处于全局范围内,这与JavaScript中的功能是常见的不同。

因此,当您第二次调用函数img时,它将尝试重新声明函数getImg

你应该定义你的函数的第一个之外,或者把它包在:

if (! function_exists('getImg')) { 
...declare function 
} 

doc:在PHP

所有函数和类都具有全局范围 - 他们可以即使在内部定义了 ,也可以在 之间调用。