views:

90

answers:

2

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 PHP, 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.

+2  A: 

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

Gumbo
+1  A: 

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]
Greg Campbell