我有这个声明变量的函数:
function imageSize($name, $nr, $category){
$path = 'ad_images/'.$category.'/'.$name.'.jpg';
$path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg';
list($width, $height) = getimagesize($path);
list($thumb_width, $thumb_height) = getimagesize($path_thumb);
${'thumb_image_' . $nr . '_width'} = $thumb_width;
${'thumb_image_' . $nr . '_height'} = $thumb_height;
${'image_' . $nr . '_width'} = $width;
${'image_' . $nr . '_height'} = $height;
}
当我回应这个时:
echo $image_1_width
它工作正常,但如果我在函数外部执行它,它不会识别变量,我怎样才能以某种方式使它们成为“全局”?
谢谢
最佳答案
我强烈建议不要使用全局。
您最好从函数返回:
function imageSize($name, $nr, $category){
$path = 'ad_images/'.$category.'/'.$name.'.jpg';
$path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg';
list($width, $height) = getimagesize($path);
list($thumb_width, $thumb_height) = getimagesize($path_thumb);
${'thumb_image_' . $nr . '_width'} = $thumb_width;
${'thumb_image_' . $nr . '_height'} = $thumb_height;
${'image_' . $nr . '_width'} = $width;
${'image_' . $nr . '_height'} = $height;
$myarr = array();
$myarr['thumb_image_' . $nr . '_width'] = $thumb_width;
$myarr['thumb_image_' . $nr . '_height'] = $thumb_height;
$myarr['image_image_' . $nr . '_width'] = $width;
$myarr['image_image_' . $nr . '_height'] = $height;
return $myarr;
}
$myImage = imageSize($name, $nr, $category);
然后你访问每个变量:
echo $myImage['thumb_image_1_width'];
echo $myImage['thumb_image_1_height'];
echo $myImage['image_1_weight'];
echo $myImage['image_1_height'];
等等
关于php - 使变量在 PHP 函数外可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1791507/