PHP:自引用数组 [英] PHP: Self-referencing array

查看:89
本文介绍了PHP:自引用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有从数组中引用数组键的方法?在代码格式中,这可能更有意义:

Is there a way of referencing an array key from within the array? This may make more sense in code format:

$array=array(
  "Key1"=>array(
    "Value1",
    "Value2"
  ),
  "Key2"=>&$this['Key1']
);

我想要的是$array['Key2']输出与$array['Key1']相同的内容.我可以在创建数组之后添加$array['Key2']=&$array['Key1'];,但是如果可能的话,希望将其全部保存在一个代码块中.

What I want is for $array['Key2'] to output the same as $array['Key1']. I can add $array['Key2']=&$array['Key1']; after the array is created, but would like to keep it all in one code block if possible.

我已经检查了有关参考的文档,以及一些此处建议的类似问题,并搜索了"php数组参考".

I've checked the docs on references, as well as some of the suggest similar questions here and a search for "php array reference".

推荐答案

事实证明,答案是肯定的.但是,它并不是一种整洁的语法,因为它使用了一种子语句,并且使当前作用域充满了额外的引用变量.

The answer to this, as it turns out, is Yes. However it is not a tidy syntax as it uses a sort of sub-statement, and leaves the current scope littered with an extra reference variable.

考虑以下代码:

<?php

  $array = array(

    // Creates Key1 and assigns the value to it
    // A copy of the value is also placed in $ref
    // At this stage, it's not a reference
    "Key1"=>($ref = array(
      "Value1",
      "Value2"
    )),

    // Now Key2 is a reference to $ref, but not to Key1
    "Key2"=>&$ref,

    // Now everything is referenced together
    "Key1"=>&$ref

  );

我很惊讶它没有错误,但是确实可以-这是证明.当然,您不会这样做,但是您可以...

I was surprised that this worked with no errors, but it does - here's the proof. Of course, you wouldn't do this, but you can...

这篇关于PHP:自引用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆