2012-11-22 14 views
5

Próbuję przepisu na przechowywanie zasobów ciągów w PHP, ale nie mogę go uruchomić. Nie jestem pewien, jak działa funkcja __get w odniesieniu do tablic i obiektów.__get zasób w PHP "Nie można użyć obiektu typu stdClass jako tablicy"

Komunikat o błędzie: „Błąd krytyczny: Nie można korzystać z obiektu typu stdClass jako tablicy w /var/www/html/workspace/srclistv2/Resource.php on line 34”

Co robię źle?

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

Oto plik zasobów nazwany QueryGenerator.res.php:

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

I tu jest miejsce próbuję to nazwać:

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

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

Odpowiedz

3

To prawda, że zdefiniuj $storage jako tablicę w klasie, ale następnie przydzielisz obiekt do niej w metodzie load ($this->storage = (object)$res;).

Dostęp do pól klasy można uzyskać, stosując następującą składnię: $object->fieldName. Tak więc w swojej metodzie __get należy zrobić:

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

myślę, że to działa bezpośrednio $ this-> storage -> $ korzeń –

+0

@ElzoValugi Jasne, że tak. Używam tego, ponieważ ja_to myślę, że jest bardziej zrozumiały dla programistów "nie-php". – Leri

+0

@PLB: Użycie tej funkcji zwraca NULL (z "innej" części czeku). Nadal dostaję z "$ resource-> query-> print" tak, jakby był tam gdzie skalar z ciągiem. –