简体   繁体   English

我可以从单独的php文件中在数组内设置变量吗?

[英]Can I set a variable inside an array from a separate php file?

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? 如果有可能,我如何使它工作?

No. You're defining $level AFTER the array has been parsed/executed/constructed by PHP. 不。您要在数组已由PHP解析/执行/构造定义$level 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的值,该值在您试图在解析时将$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. 让您了解时间旅行的情况。

Consider using level as a parameter. 考虑使用级别作为参数。

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"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM