duanchi8836 2014-08-20 21:45
浏览 18
已采纳

变量是否可以引用自身

I've never seen something like this in a language, but I'm working with a PHP array and it would quite useful, but more than any thing, I'm curious.

Is it possible for a regular variable to reference itself. For example:

    $variable_array = array(1, 2);
    $variable_array = array_merge(self, array(3, 4));

or

    $variable_string = 'This is a string';
    $variable_string = explode(' ', self);

Where self is the variable itself, like this is when working with objects. Now, I know someone is going to ask why not just call the variable again, and that is what I normally do in this case. However, for readability when dealing with long names, such as named indexes in arrays, this would be useful.

Does PHP, or any language at all do this or something similar?

  • 写回答

4条回答 默认 最新

  • dtjo51649 2014-08-20 22:53
    关注

    So, thanks to RandomSeed reminding me of variable references, I came up with what I think is the closest solution I'm likely to get.

    Take this as an example:

       $array['index1']['index2']['index3']['index4'];
       $array['index1']['index2']['index3']['index4'] = array_merge(
             $array['index1']['index2']['index3']['index4'], 
             array('test' => 'answer'),
             array('test2' => 'answer'));
    

    This is unappealing in my eyes, and a bit difficult to follow, especially if there are multiple of these on a page, or in a controller action.

    So this is an alternative:

       $self = &$array['index1']['index2']['index3']['index4'];
       $array['index1']['index2']['index3']['index4'] = array_merge(
             $self, 
             array('test' => 'answer'),
             array('test2' => 'answer'));
    

    A Quick test on my live environment seems to verify that it works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?