开发者

"Directly accessing" return values without referencing

Look at this ruby example:

puts ["Dog","Cat","Gates"][1]

This will output Cat as ruby allows me to directly access the "anonymous" array created.

If I try this in PH开发者_如何学编程P, however:

echo array("Dog","Cat,"Gates")[1]

This won't work.

  • What is this called, not only concerning arrays but all functions?
  • Where else is it possible?

Feel free to change the question title when you know how this "feature" is called.


PHP has no such language construct. It was proposed for PHP 6 but got declined.


In Ruby, [] is just a method call (obj[1] is syntactic sugar for obj.[](1)) so there's no semantic difference between ["Dog", "Cat", "Gates"][1] and ["Dog", "Cat", "Gates"].slice(1). Many syntactic constructs that appear to be "operators" in Ruby are really methods, and they can generally be defined on your own custom classes. For example:

class Foo
  def [](index)
    puts "you tried to get something at #{index}"
  end
end

f = Foo.new
f[12]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜