我可以从一个单独的php文件中设置一个变量吗?

时间:2021-12-14 08:10:05

Let's say I have a file effects.php with an array in it like

假设我有一个文件effects.php,里面有一个数组

$techniqueDescriptions = array("damage" => "Deals ".$level." damage.");

And I have another file display.php that both gets the level and displays the attack like.

我有另一个文件display.php,它们都获得级别并显示攻击。

$level = $user->data["level"];
echo $techniqueDescriptions["damage"];

I tried the setup above and it gives "Deals damage", even if I declare it global in both files. How can I get it to work, if it's possible?

我尝试了上面的设置,它给出了“交易损害”,即使我在两个文件中都声明它是全局的。如果可能的话,我怎样才能让它发挥作用?

2 个解决方案

#1


3  

Consider using level as a parameter.

考虑使用level作为参数。

effects.php:

effects.php:

function techniqueDescriptions($level) {
  return array("damage" => "Deals ".$level." damage.");
}

display.php:

Display.php的:

require_once('effects.php')
$level = $user->data["level"];
echo techniqueDescriptions($level)["damage"];

#2


4  

No. You're defining $level AFTER the array has been parsed/executed/constructed by PHP. PHP cannot "reach back in time" to retroactively insert a value for $level which didn't exist at the time you tried to insert $level into the array when it was being parsed.

不。您在PHP解析/执行/构造数组后定义了$ level。 PHP无法“及时回溯”以追溯性地插入$ level的值,当您尝试在解析数据时将$ level插入数组时该值不存在。

You'd have to do something like

你必须做类似的事情

$level = 'foo';
include('array_gets_defined_here.php');
echo $techniqueDescriptions['damage'];

Doing it the other way around:

反过来做:

include('array_gets_defined_here.php');
$level = 'foo';
echo $techniqueDescriptions['damage'];

gets you into the time travel situation.

让你进入时间旅行的情况。

#1


3  

Consider using level as a parameter.

考虑使用level作为参数。

effects.php:

effects.php:

function techniqueDescriptions($level) {
  return array("damage" => "Deals ".$level." damage.");
}

display.php:

Display.php的:

require_once('effects.php')
$level = $user->data["level"];
echo techniqueDescriptions($level)["damage"];

#2


4  

No. You're defining $level AFTER the array has been parsed/executed/constructed by PHP. PHP cannot "reach back in time" to retroactively insert a value for $level which didn't exist at the time you tried to insert $level into the array when it was being parsed.

不。您在PHP解析/执行/构造数组后定义了$ level。 PHP无法“及时回溯”以追溯性地插入$ level的值,当您尝试在解析数据时将$ level插入数组时该值不存在。

You'd have to do something like

你必须做类似的事情

$level = 'foo';
include('array_gets_defined_here.php');
echo $techniqueDescriptions['damage'];

Doing it the other way around:

反过来做:

include('array_gets_defined_here.php');
$level = 'foo';
echo $techniqueDescriptions['damage'];

gets you into the time travel situation.

让你进入时间旅行的情况。