我以前问过一个问题,基本上把$null = null
方法作为给定的,在PHP中返回空引用。
无论如何,如果不清楚;什么(其他,如果有)的方式存在返回null
从一个函数引用在PHP?我特别问关于返回空引用,而不是关于三元运算符问题,浮出水面来解释我的链接问题。
function &return_null(){
return null;
}
$null_ref = return_null(); // fails
然而:function &return_null(){
$null = null;
return $null;
}
$null_ref = return_null(); // succeeds
我问这个问题是因为我在创建可重用库时有点强迫症;我真的喜欢干净的代码,不管它在给定的语言中有多干净。使用占位符$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;
}
在这个ArrayPath
类中还有setByPath()
、issetByPath()
和unsetByPath()
。我给这些静态方法添加了重载的别名。在构造实例时,将数组传递给构造函数(和分隔符),魔术方法使用实例的引用数组调用静态方法。到目前为止,它运行得很好。此外,我还编写了一个别名函数array_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"
}
}
}
*/
我对我的代码也有点挑剔。这里没有功能上的区别,但我认为这个看起来和读起来更好。但那只是我个人的喜好。
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;
}
我不确定"引用"answers"干净的代码"是否在一起…(
无论如何,引用不是指向对象/值的指针,而是指向变量的指针。因此,只有变量是合适的目标。所述变量可以"命名"一个对象/值(即:被赋值),如文中所示。然而,post并没有返回一个"空引用"——它返回一个对一个变量的引用,该变量"命名"为null。(然后人们想知道为什么我在处理高级语言/概念时拒绝使用变量"存储对对象的引用"这一术语…)
快乐编码。
至于通过引用返回,其他方式不起作用
http://www.php.net/manual/en/language.references.return.php只能通过函数的引用返回变量,不能有其他方法。
您可能要重新考虑是否引用是您真正需要的东西,特别是您已经将$array
作为引用传递并返回它
对于您的特定问题的解决方案是概括您的代码:
function &getByPath(array &$array, $path, $delimiter = '/'){
if (!is_array($path)){
$path = explode($delimiter, $path);
}
$current =& $array;
foreach ($path as $part) {
$current =& $current[$part];
}
return $current;
}
现在没有返回空值。相反,函数将以指定的路径返回元素,即使它还不存在(路径将被添加到数组中并使用null
初始化)。
$element =& getByPath($array, 'hallo/world');
isset($element); // if the element didn't exist, this will return false
$element = 'hi'; // we can set the element, even if it did not exist
哦,顺便说一句:没有其他方法可以通过引用返回null
,我也不明白为什么你有这个问题;)引用返回意味着返回一个变量,而null
不是。
我只是这样做(不初始化$null
):
return $null;
它的好处就像NikiC提到的那样,您可以简单地使用isset($result)
来确定结果是否存在。