5

文字列リソースを PHP に格納する方法のレシピを試していますが、うまく動作しないようです。配列とオブジェクトに関して __get 関数がどのように機能するかについては、少しわかりません。

エラー メッセージ: 「致命的なエラー: 34 行目の /var/www/html/workspace/srclistv2/Resource.php で stdClass 型のオブジェクトを配列として使用できません」

私は何を間違っていますか?

/**
 * 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;
    }
}

QueryGenerator.res.php という名前のリソース ファイルは次のとおりです。

$res = array(
    'query' => array(
        'print' => 'select * from source prints',
        'web'  => 'select * from source web',
    )
);

そして、ここに私がそれを呼ぼうとしている場所があります:

    $resource = new Resource("QueryGenerator.res");

    $query = $resource->query->print;
4

1 に答える 1

3

クラスで配列として定義するのは事実ですが、メソッド ( )$storageでそれにオブジェクトを割り当てます。load$this->storage = (object)$res;

クラスのフィールドには、次の構文でアクセスできます: $object->fieldName. したがって、__getメソッドでは次のことを行う必要があります。

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;
}
于 2012-11-22T12:39:58.167 に答える