有没有可能在同一个数组中,用一个元素引用另一个元素?
比如我们想要创建这样的一个数组:
$a = array(
'base_url' => 'https://rh.example.com',
'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$this['base_url'],
);
当然,它不起作用是因为
$this
是针对类而不是数组的。那么有没有替代方案呢?有没有可能在同一个数组中,用一个元素引用另一个元素?
比如我们想要创建这样的一个数组:
$a = array(
'base_url' => 'https://rh.example.com',
'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$this['base_url'],
);
$this
是针对类而不是数组的。那么有没有替代方案呢?不,无法以这种方式实现。您无法在同一数组的上下文中引用该数组。但是这里有一个解决方法:
$a = array(
'base_url' => ($base_url = 'https://rh.example.com'),
'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$base_url,
);
$a['base_url'] = 'https://rh.example.com';
$a['URL_SLO_OpenAM_OIC'] = 'https://openam.example.com/openam/UI/Logout?goto='.$a['base_url'];
你不能将一个数组元素引用到另一个元素。数组没有这样的功能。如果你这样做,它会给你一个未定义的变量错误。
回答你的问题,你可以将值存储到另一个变量中,在初始化数组时使用该变量。
$base_url = 'https://rh.example.com';
$a = array(
'base_url' => $base_url,
'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$base_url,);
你不能像对待数据一样任意操作数组。但是你可以使用对象来实现这一点:
$myCustomArray = new stdClass;
$myCustomArray->base_url = 'https://rh.example.com';
$myCustomArray->URL_SLO_OpenAM_OIC = function () { echo 'https://openam.example.com/openam/UI/Logout?goto='.$this->base_url; };
然后执行:$myCustomArray->URL_SLO_OpenAM_OIC();
另一种方法是在赋值后使用令牌替换值,对于简单情况使用令牌。
<?php
function substitutor(array $array) {
foreach ($array as $key => $value) {
if(preg_match('/@(\w+)@/', $value, $match)) {
$array[$key] = str_replace($match[0], $array[$match[1]], $value);
}
};
return $array;
}
$array = array(
'foo' => 'bar',
'baz' => 'some' . '@foo@'
);
var_dump($array);
$substituted = substitutor($array);
var_dump($substituted);
输出:
array(2) {
["foo"]=>
string(3) "bar"
["baz"]=>
string(9) "some@foo@"
}
array(2) {
["foo"]=>
string(3) "bar"
["baz"]=>
string(7) "somebar"
}