在数组元素中引用另一个相同数组的元素。

3

有没有可能在同一个数组中,用一个元素引用另一个元素?

比如我们想要创建这样的一个数组:

$a = array(
    'base_url' => 'https://rh.example.com',
    'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$this['base_url'],
);

当然,它不起作用是因为$this是针对类而不是数组的。那么有没有替代方案呢?

你为什么要使用 $this?你是在类的范围内使用它吗? - André Ferraz
1
不,我只是想解释一下我所说的引用的含义。该数组不在类的范围内。 - rsabir
1
然而,您不应该使用关键字$this(因为它代表一个对象),您不能将其表示为数组。 - André Ferraz
是的,我同意你的观点。请看我的更新并告诉我现在我的问题是否更容易理解了? - rsabir
这在逻辑上是正确的吗?一个变量在自身内部调用自身?你不需要计算机科学学位来知道这一点。 - André Ferraz
1
我认为这违反了数组的概念,数组是用于对象能力的。 - Fil
5个回答

9

不,无法以这种方式实现。您无法在同一数组的上下文中引用该数组。但是这里有一个解决方法:

$a = array(
    'base_url' => ($base_url = 'https://rh.example.com'),
    'URL_SLO_OpenAM_OIC' => 'https://openam.example.com/openam/UI/Logout?goto='.$base_url,
);

2
另一种方法是逐个向数组添加元素。
$a['base_url'] = 'https://rh.example.com';
$a['URL_SLO_OpenAM_OIC'] = 'https://openam.example.com/openam/UI/Logout?goto='.$a['base_url'];

1

你不能将一个数组元素引用到另一个元素。数组没有这样的功能。如果你这样做,它会给你一个未定义的变量错误。

回答你的问题,你可以将值存储到另一个变量中,在初始化数组时使用该变量。

$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,);

1

你不能像对待数据一样任意操作数组。但是你可以使用对象来实现这一点:

$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();


0

另一种方法是在赋值后使用令牌替换值,对于简单情况使用令牌。

<?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"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接