在PHP中使用函数外部变量?

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)

等等


Jan*_*čič 9

您必须在函数之外定义它们.在函数内部使用global关键字之前使用它们:

$someVar = null;

function SomeFunc () {
    global $someVar;
    // change $someVar
}

// somewhere later
SomeFunc ();
echo $someVar;
Run Code Online (Sandbox Code Playgroud)

但请注意,这是一个非常糟糕的设计选择!

  • 同意.我建议让函数将这些值作为数组返回,而不是使用全局变量. (4认同)
  • 如果你使用全局变量,你永远不知道何时以及谁将修改它们并且它会破坏代码的流程.查看其他答案中的一些建议,以获取有关如何重写函数的线索(提示:返回您需要的东西) (3认同)