__get resource in PHP "Cannot use object of type stdClass as array"

arrays, hash, object, php, resources

Solution

It's true that you define `$storage` as an array in your class but then you assigne object to it in `load` method (`$this->storage = (object)$res;`).

Fields of class can be accessed with following syntax: `$object->fieldName`. So in your `__get` method you should do:

public function __get($root)
{
    if (is_array($this->storage)) //You re-assign $storage in a condition so it may be array.
        return isset($this->storage[$root]) ? $this->storage[$root] : null;
    else
        return isset($this->storage->{$root}) ? $this->storage->{$root} : null;
}

Problem

I'm trying out a recipe on how to store string resources in PHP, but I can't seem to get it to work. I am a little unsure on how the __get function works in relation to arrays and objects. Error Message: "Fatal error: Cannot use object of type stdClass as array in /var/www/html/workspace/srclistv2/Resource.php on line 34" What am I doing wrong? ``` /** * Stores the res file-array to be used as a partt of the resource object. */ class Resource { var $resource; var $storage = array(); public function __construct($resource) { $this->resource = $resource; $this->load(); } private function load() { $location = $this->resource . '.php'; if(file_exists($location)) { require_once $location; if(isset($res)) { $this->storage = (object)$res; unset($res); } } } public function __get($root) { return isset($this->storage[$root]) ? $this->storage[$root] : null; } } ``` Here is the resource file named QueryGenerator.res.php: ``` $res = array( 'query' => array( 'print' => 'select * from source prints', 'web' => 'select * from source web', ) ); ``` And here is the place I'm trying to call it: ``` $resource = new Resource("QueryGenerator.res"); $query = $resource->query->print; ```

Original source