PHP

在5.4之前我们直接获取数组的值得方法如下

<?php
    $str = 'a;b;c;d';
    list($value) = explode(';',$str);
    echo $value;

  

结果为: a

但是5.4的Array derenferencing 是什么意思呢?如下

<?php
    $str = 'a;b;c;d';
    $value = explode(';',$str)[0];
    echo $value;

  

结果同为:a

其实很简单,但是我们运用当中可能会出现一些的问题。比如

<?php
    class Example{
        
        private $value = [];
        
        public function getValue(){
            
            return $this->value;
            
        }
    }
    
    $example = new Example;
    
    $example->getValue()['test'] = 'test';
    
    echo $example->getValue()['test'];

  

会出现如下报错

Notice: Undefined index: test in D:Phpxampphtdocs	estPHP - 5.xexample.php on line 17

上面的代码混淆了返回值和返回引用,在PHP中,除非你显示的指定返回引用,否则对于数组PHP是值返回,也就是数组的拷贝。因此上面代码对返回数组赋值,实际是对拷贝数组进行赋值,非原数组赋值。

下面是一种可能的解决办法,输出拷贝的数组,而不是原数组:

$vals = $config->getValues(); 
$vals['test'] = 'test'; 
echo $vals['test'];  //test

  

如果你就是想要改变原数组,也就是要反回数组引用,就是显示指定返回引用即可

<?php
    class Example{
        
        private $value = [];
        
        public function &getValue(){
            
            return $this->value;
            
        }
    }
    
    $example = new Example;
    
    $example->getValue()['test'] = 'test';

    echo $example->getValue()['test'];

上面的例子输出:test

原文地址:https://www.cnblogs.com/uduemc/p/3998750.html