Is it possible to reference a specific element of an anonymous array in PHP?
This is probably a simple question, and I'm afraid the answer might be "no", but...
Here's a simple piece of code:
function func1() {
$bt = debug_backtrace();
print "Previous function was " . $bt[1]['function'] . "n";
}
Now... Can this be done without the temporary variable? In another language, I might expect to be able to say:
function func1() {
print "Previous function was " . (debug_backtrace())[1]['function'] . "n";
}
Alas, in PHP, this results in an error:
PHP Parse error: syntax error, unexpected '[' ...
If it can't be done, it can't be done, and I'll use a temporary variable, but I'd rather not.
No, direct dereferencing is unfortunately not supported in current versions of PHP, but will apparently come in PHP 5.4.
Also see Terminology question on "dereferencing"?.
Array dereferencing is not available in PHP 5.3 right now, but it will be available in PHP 5.4 (PHP 5.4.0 RC2 is currently available for you to tinker with). In the meantime, you can use end()
, reset()
, or a helper function to get what you want.
$a = array('a','b','c');
echo reset($a); // echoes 'a'
echo end($a); // echoes 'c'
echo dereference($a, 1); // echoes 'b'
function dereference($arr, $key) {
if(array_key_exists($key, $arr)) {
return $array[$key];
} else {
trigger_error('Undefined index: '.$key); // This would be the standard
return null;
}
}
Note that end()
and current()
will reset the array's internal pointer, so be careful.
For your convenience, if you'll be chaining your dereferences this might come in handy:
function chained_dereference($arr, $keys) {
foreach($keys as $key) {
$arr = dereference($arr, $key);
}
return $arr;
}
// chained_dereference(debug_backtrace(), array(1, 'function')) = debug_backtrace()[1]['function']
链接地址: http://www.djcxy.com/p/69578.html
上一篇: 使用函数访问PHP数组元素?