2012-11-22 6 views
5

文字列リソースをPHPに格納する方法を試していますが、動作させることができません。私は配列とオブジェクトに関して__get関数がどのように動作するかについて少し不安です。PHPの__getリソース「配列としてstdClass型のオブジェクトを使用できません」

エラーメッセージ:「致命的なエラー:行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; 

答えて

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; 
} 
+0

私はこれが直接の$ this - >ストレージうまくいくと思う - > $ルート –

+0

@ElzoValugi確かに、それはありません。私はこれを使用します。なぜなら、 "非PHP"プログラマーにとってはわかりやすいからです。 – Leri

+0

@PLB:この関数を使用すると、NULL(チェックの「else」部分から)が返されます。 "$ resource-> query-> print"が文字列のスカラーと同じようになっています。 –

関連する問題