5

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;

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

@ElzoValugi Sure, it does. I use this because I think it's more understandable for "non-php" programmers.
@PLB : Using this function returns NULL (from the "else"-part of the check). Still getting with "$resource->query->print" as if it where a scalar with a string.
@JonasBallestad You can access it like: $resource->query['print'].
@PLB So this means that going (object)$res only "objectifies" the top level, but keeps the lower ones at array behaviour?
@JonasBallestad Yes, when $res is an array it's exact behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.