PHP 和返回空引用(重新访问)

Dan*_*ugg 4 php null reference return-by-reference

我之前问过一个问题,基本上采用$null = null了给定的方法,在 PHP 中返回一个空引用。

经过一些粗略的谷歌搜索后,我没有出现太多。让我假设上述方法是最好的(只读)方法。然而,对我来说,PHP 将(仍然)无法支持这样的功能似乎很奇怪。

不管怎样,如果不清楚;在 PHP 中通过引用从函数返回什么(其他,如果有的话)方法null?我特别询问返回空引用,而不是为了解释我的链接问题而浮出水面的三元运算符问题。

例如:

function &return_null(){
    return null;
}

$null_ref = return_null(); // fails
Run Code Online (Sandbox Code Playgroud)

然而:

function &return_null(){
    $null = null;
    return $null;
}

$null_ref = return_null(); // succeeds
Run Code Online (Sandbox Code Playgroud)

我问是因为我在创建可重用库时有点强迫症;我真的很喜欢干净的代码,不管它在给定的语言中可以变得多么干净。使用占位符$null = null会使我的皮肤爬行,尽管它实现了所需的功能。


为了完整起见@ yes123,这里是这个问题所在的方法片段:

public static function &getByPath(Array &$array, $path, $delimiter){
    if(!is_array($path)){
        $path = explode($delimiter, $path);
    }
    $null = null;
    while(!empty($path)){
        $key = array_shift($path);
        if(!isset($array[$key])){
            return $null;
        }
        if(!empty($path) && !is_array($array[$key])){
            return $null;
        }
        $array = &$array[$key];
    }
    return $array;
}
Run Code Online (Sandbox Code Playgroud)

在这个类中还有setByPath(), issetByPath(), 和。我用重载魔法给这些静态方法取了别名。当构造一个实例时,一个数组被传递给构造函数(连同一个分隔符),魔术方法使用实例的引用数组调用静态方法。到目前为止,它工作得非常好。此外,我编写了一个别名函数,它只返回一个实例。例如,可以这样做:unsetByPath()ArrayPatharray_path()

$array = array(
    'foo' => array(
        'bar' => array(
            'hello' => 'world',
        ),
    ),
);

array_path($array, '/')->{'foo/bar/hello'} = 'universe';
var_dump($array);

/*
array(1) {
  ["foo"]=>
  array(1) {
    ["bar"]=>
    array(1) {
      ["hello"]=>
      string(8) "universe"
    }
  }
}
*/
Run Code Online (Sandbox Code Playgroud)

Dan*_*lad 5

我也有点讨厌我的代码。这里没有功能差异,但我认为这看起来和阅读起来更好。但这只是我个人的喜好。

function &getByPath(array &$array, $path, $delimiter = '/'){
    $result = NULL;

    // do work here and assign as ref to $result if we found something to return
    // if nothing is found that can be returned we will be returning a reference to a variable containing the value NULL

    return $result;
}
Run Code Online (Sandbox Code Playgroud)


小智 4

我不确定“引用”和“干净的代码”是否可以放在一起......:(

无论如何,引用不是“指向”对象/值的指针,而是“指向”变量的指针。因此,只有变量才是合适的目标。所述变量可以“命名”一个对象/值(读取:分配一个值),如帖子中所示。但是,该帖子不会返回“空引用”——它返回对“命名” null 的变量的引用

(然后人们想知道为什么我在处理高级语言/概念时拒绝变量“存储对对象的引用”这一术语......)

快乐编码。