PHP 中是否可以引用匿名数组的特定元素?
这可能是一个简单的问题,恐怕答案可能是“否”,但是...
这是一段简单的代码:
function func1() {
$bt = debug_backtrace();
print "Previous function was " . $bt[1]['function'] . "\n";
}
现在...可以在没有临时变量的情况下完成吗?用另一种语言,我可能期望能够说:
function func1() {
print "Previous function was " . (debug_backtrace())[1]['function'] . "\n";
}
唉,在 PHP 中,这会导致错误:
PHP Parse error: syntax error, unexpected '[' ...
如果做不到,那就做不到,我将使用临时变量,但我宁愿不。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不幸的是,当前版本的 PHP 不支持直接取消引用,但显然会在 PHP 5.4 中支持。
另请参阅有关“取消引用”的术语问题?。
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"?.
数组解引用目前在 PHP 5.3 中不可用,但将在 PHP 5.4 中可用(PHP 5.4.0 RC2 目前可用供您修改)。同时,您可以使用
end()
、reset()
或辅助函数来获取您想要的内容。请注意,
end()
和current()
将重置数组的内部指针,因此请小心。为了您的方便,如果您要链接取消引用,这可能会派上用场:
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.Note that
end()
andcurrent()
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: