我有一个函数
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);
为什么我总是收到此错误?
<小时 />无法重新声明 App\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');
}
}
}
你的函数应该像这样在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) {
..........
}
在PHP中,函数总是在全局范围内,这与JavaScript不同,JavaScript中的函数是通用的。
因此,当您第二次调用函数img
时,它将尝试重新声明函数getImg
。
你应该在第一个函数之外定义你的函数,或者把它包装在:
if ( ! function_exists('getImg')) {
...declare function
}
从文档中:
PHP 中的所有函数和类都具有全局范围 - 它们可以是 在函数外部调用,即使它们是在函数内部和 Vice 中定义的 反之亦然。