php - 使变量在 PHP 函数外可用?

标签 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;
}

当我回应这个时:

   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/

相关文章:

javascript - 如何验证动态创建的具有时间值的文本框

PHP 比较日期时间和时区

php - export mysql中自增列说明

php - foreach 的问题

php - 如何在我的设置是 Windows 10 主机中的 Vagrant Ubuntu 16.06 的 Visual Studio Code 中配置 PHP 可执行文件

php - 从 API 获取数据时诊断瓶颈

php - html 在不工作后用 php 提交按钮

php - 通过 Javascript 传递变量

php - 如何在 setcookies() 中设置域

php - 在 while 循环(作用域)之外使用变量