该代码会回显“之前”,我的目标-6ren">
gpt4 book ai didi

php - 仅在需要时初始化数组中的变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:47 25 4
gpt4 key购买 nike

这里有一个小模型来描述我的困境:

<?php
$var = "Before";

function getVar(){
global $var;

return $var;
}

$array = Array(
"variable" => "Var = " . getVar()
);

$var = "After";

echo $array['variable'];
?>

该代码会回显“之前”,我的目标是让它回显“之后”。我意识到这就是 PHP 应该 的工作方式,但是它对于数组仅在调用时执行 getVar() 至关重要。

我该怎么做?

最佳答案

你不能这样做,因为数组声明会初始化它 - 所以你在数组的“用法”和它的定义中混合调用函数。没有“用法”:到那一刻数组已经定义

但是,答案可能是使用 ArrayAccess ,像这样:

class XArray implements ArrayAccess
{
private $storage = [];

public function __construct()
{
$this->storage = func_get_args();
}

public function offsetSet($offset, $value)
{
if(is_null($offset))
{
$this->storage[] = $value;
}
else
{
$this->storage[$offset] = $value;
}
}

public function offsetExists($offset)
{
return isset($this->storage[$offset]);
}

public function offsetUnset($offset)
{
unset($this->storage[$offset]);
}

public function offsetGet($offset)
{
if(!isset($this->storage[$offset]))
{
return null;
}
return is_callable($this->storage[$offset])?
call_user_func($this->storage[$offset]):
$this->storage[$offset];
}
}

function getVar()
{
global $var;
return $var;
}

$var = 'Before Init';
$array = new XArray('foo', 'getVar', 'bar');
$var = 'After Init';
var_dump($array[1]);//'After Init'

-即尝试在实际发生时调用元素内部的数据。您可能希望有不同的构造函数(用于关联数组)- 但显示了总体思路。

关于php - 仅在需要时初始化数组中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19397522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com