0

When reviewing some code, I found the following construct, specifically the array ($this[$key]). How does it work? Where does it put the values? Where can I find it documented?

public function __get($key)
{
    return $this[$key];
}

Answer: Thanks Mario. It's implemented by adding the ArrayAccess interface to the object and implementing offsetGet and offsetSet methods.

Peter Wiseman
  • 334
  • 3
  • 6
  • See http://php.net/manual/en/language.oop5.magic.php and http://php.net/manual/en/class.arrayaccess.php – mario May 05 '16 at 13:07
  • Aha - arrayaccess. Thanks mario. – Peter Wiseman May 05 '16 at 13:23
  • Hard to tell without context. This one is more likely derived from `ArrayObject`. With `ArrayAccess` you'd use `offsetGet` instead of `__get` usually. – mario May 05 '16 at 13:25
  • I'm working through Laravel. The Container class uses this method, implementing both the magic methods, and the ArrayAccess interface to allow either calling method to work. – Peter Wiseman May 05 '16 at 13:34

1 Answers1

2

That's a getter, there's not much to it than what you see. You access a private object's properties.

http://php.net/manual/en/language.oop5.overloading.php#object.get

yBrodsky
  • 4,652
  • 1
  • 16
  • 29
  • It's the array access bit that I'm not understanding. $this[$key] – Peter Wiseman May 05 '16 at 13:22
  • $this is a private variable you have in the class. For example you have a private variable $name; With this function you get the value of $this['name'] if you call the function __get('name') – yBrodsky May 05 '16 at 13:25