2012-11-22 37 views
5

我想了解如何在PHP中存儲字符串資源的配方,但我似乎無法讓它工作。我有點不確定__get函數如何與數組和對象相關。__get資源在PHP中「不能使用stdClass類型的對象作爲數組」

錯誤消息:「致命錯誤:在/var/www/html/workspace/srclistv2/Resource.php在線34不能使用類型爲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

我想這樣的作品直接這個 - $>存儲 - > $根 –

+0

@ElzoValugi當然,它的作用。我使用這個是因爲我認爲「非php」程序員更容易理解。 – Leri

+0

@PLB:使用此函數將返回NULL(來自檢查的「其他」部分)。仍在使用「$ resource-> query-> print」,就好像它是一個帶有字符串的標量。 –

相關問題