duanpo2037 2018-01-19 17:41
浏览 168
已采纳

如何使用函数将全局变量包含在另一个函数中?

I have a rather large set of global variables that I want to be able to use within other functions across various files. I know that to use these variables within other functions I need to use the global keyword to include the variable names.

Everything works when I do that, but since there are so many variables, I'd rather create a function that allows me to include the global declaration within the function, with the specific chunk of variables I need being included using a function parameter.

For illustrative purposes, this works:

variables.php (declared before other files are included)

$var1 = 'abc';
$var2 = 'def';
$var3 = 'ghi';

other-function-file.php

function my_function() {
  global $var1, $var2, $var3;
  return $var1 . $var2 . $var3;
}

But this does not work:

variables.php

$var1 = 'abc';
$var2 = 'def';
$var3 = 'ghi';

globals-list-declaration.php

global $var1, $var2, $var3;

globals-include-function.php

function include_globals() {
  include_once('globals-list-declaration.php');
}

other-function-file.php

function my_function() {
  include_globals();
  return $var1 . $var2 . $var3;
}

This is a little simplified, as there multiple variable and global declaration files, and I'll be able to specify which file to include by passing in a parameter to include_globals() in globals-include-function.php.

But for some reason, when I move the hard-typed global $var1, $var2, $var3; to a seperate file and include it in the exact same location (either through include or the include_globals() function decribed above), it ceases to work.

How can I make this work or is it even possible?

Thanks!

  • 写回答

2条回答 默认 最新

  • dongshuan8722 2018-01-19 17:51
    关注

    From the docs http://php.net/manual/en/function.include.php:

    If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function

    In other words, if can't use this:

    function include_globals() {
        include_once('globals-list-declaration.php');
    }
    

    Because the definition of globals will only exists inside this function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行