Search code examples
phplaravellaravel-5magic-methods

How does Laravel use the app object like its an array?


I am setting up an application in PHP, trying to follow some of the conventions laid down in Laravel, I can see there are lots of references to $this->app["some_var"];

But in my app it throws an error saying "Cannot use object as an array".

I am aware that Laravel uses magic methods such as __get() and __set() which I have included, however I still get the same results.

The magic getter and setter code I have used in the parent class of my App object

  /**
  * Dynamically access container services.
  *
  * @param  string  $key
  * @return mixed
  */
  public function __get($key)
  {
    return $this[$key];
  }

  /**
   * Dynamically set container services.
   *
   * @param  string  $key
   * @param  mixed   $value
   * @return void
   */
  public function __set($key, $value)
  {
    $this[$key] = $value;
  }

Expected result is for it to access any property that is innaccessable on the object?

Currently throws a Fatal error: Uncaught Error: Cannot use object Application as type of array.


Solution

  • You need to implement ArrayAccess See below code from https://www.php.net/manual/en/class.arrayaccess.php The following code stores the array values in $container array and proxies $obj['key'] to this array object

    <?php
    class obj implements ArrayAccess {
        private $container = array();
    
        public function __construct() {
            $this->container = array(
                "one"   => 1,
                "two"   => 2,
                "three" => 3,
            );
        }
    
        public function offsetSet($offset, $value) {
            if (is_null($offset)) {
                $this->container[] = $value;
            } else {
                $this->container[$offset] = $value;
            }
        }
    
        public function offsetExists($offset) {
            return isset($this->container[$offset]);
        }
    
        public function offsetUnset($offset) {
            unset($this->container[$offset]);
        }
    
        public function offsetGet($offset) {
            return isset($this->container[$offset]) ? $this->container[$offset] : null;
        }
    }
    
    $obj = new obj;
    
    var_dump(isset($obj["two"]));
    var_dump($obj["two"]);
    unset($obj["two"]);
    var_dump(isset($obj["two"]));
    $obj["two"] = "A value";
    var_dump($obj["two"]);
    $obj[] = 'Append 1';
    $obj[] = 'Append 2';
    $obj[] = 'Append 3';
    print_r($obj);
    ?>