如何在不使用全局 php 的情况下获取函数外部的$var


How to get $var outside the function without using global php?

这里需要小帮助。正在阅读在函数中添加全局变量并在外部调用它是多么糟糕,但在外面放置变量时遇到了小问题。全球帮助,但我也想安全,因为我在这里处理一些文件

我的循环是这样的

<?php 
require_once('functions.php'); 
?>
<?php 
foreach( $files as $key=> $file ){  
global $download_link;
get_file_info($key,$file);
?>
<span><a href="<?php echo $download_link ?>"><?php echo $file->name ?></a></span>
<?php } ?>

我函数的一部分.php/大约 150 行长,但这是主要截图

function  get_file_info($key,$file){
global $download_link;
$access     = explode(",",$file->access);
$permission = in_array(1,$access);
if($permission){
$download_link = 'ok to download';
}else{
$download_link = 'canot download';
}

}

除了链接 var 之外,我还有一些其他的,如日期、计数器等,但它们都受到某些条件的约束。

我试着做

返回 $link; 在函数末尾,而不是使用全局但得到未定义的变量错误;

所以这里的基本问题是,如何在不使用全局的情况下获取函数外部的download_link变量?

通过修改文件类可以更轻松地执行此操作

class File {
    # ...
    function get_url() {
        return in_array(1, explode(',', $this->access))
            ? $this->url  # return the file's url
            : "/path/to/subscribe" # return a default path for non-access
        ;
    }
}

您的 HTML 将按如下方式使用它

<?php
foreach ($files as $file) {
    echo '<a href="'.$file->get_url().'">Download this '.$file->name.'</a>';
}

既然你只是用get_file_info来设置$download_link,为什么不直接返回$permission并在函数外定义$download_link呢?

<?php 
function  get_file_info($key,$file){
    $access     = explode(",",$file->access);
    $permission = in_array(1,$access);
    return $permission;
}
foreach( $files as $key=> $file ){  
    $download_link = 'canot download';
    if(get_file_info($key,$file)) {
        download_link = 'ok to download';
    }
    echo '<span><a href="$download_link ">'. $file->name . '</a></span>';
} 
?>
<</div> div class="answers">

你可以像这样改变你的循环:

    <?php 
require_once('functions.php'); 
?>
<?php 
foreach( $files as $key=> $file ){  
   $download_link = get_file_info($key,$file);
?>
<span><a href="<?php echo $download_link ?>"><?php echo $file->name ?></a></span>
<?php } ?>

和你的函数代码:

  function  get_file_info($key,$file){
 $access     = explode(",",$file->access);
 $permission = in_array(1,$access);
  if($permission){
return  'ok to download';
  }
  else {
return 'canot download';
  }
 }