开发者

"Directly accessing" return values without referencing

开发者 https://www.devze.com 2022-12-24 18:02 出处:网络
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.

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

精彩评论

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