6 php
我有这个声明变量的函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
当我回应这个:
echo $image_1_width
Run Code Online (Sandbox Code Playgroud)
它工作正常,但如果我在功能外面它不会识别变量,我怎么能以某种方式使它们'全局'?
谢谢
Liz*_*ard 13
我强烈建议不要使用全局.
可能最好的是你从函数返回:
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;
}
Run Code Online (Sandbox Code Playgroud)
$myImage = imageSize($name, $nr, $category);
然后你访问每个var:
echo $myImage['thumb_image_1_width'];
echo $myImage['thumb_image_1_height'];
echo $myImage['image_1_weight'];
echo $myImage['image_1_height'];
Run Code Online (Sandbox Code Playgroud)
等等
您必须在函数之外定义它们.在函数内部使用global关键字之前使用它们:
$someVar = null;
function SomeFunc () {
global $someVar;
// change $someVar
}
// somewhere later
SomeFunc ();
echo $someVar;
Run Code Online (Sandbox Code Playgroud)
但请注意,这是一个非常糟糕的设计选择!