2012-11-22 6 views
5

मैं PHP में स्ट्रिंग संसाधनों को स्टोर करने के तरीके पर एक नुस्खा का प्रयास कर रहा हूं, लेकिन मुझे इसे काम करने के लिए प्रतीत नहीं होता है। मैं थोड़ा अनिश्चित हूं कि __get फ़ंक्शन एरे और ऑब्जेक्ट्स के संबंध में कैसे काम करता है।PHP में __get संसाधन "स्टेड क्लास प्रकार के ऑब्जेक्ट का उपयोग सरणी के रूप में नहीं कर सकता"

त्रुटि संदेश: "गंभीर त्रुटि: लाइन 34 पर /var/www/html/workspace/srclistv2/Resource.php में सरणी के रूप में प्रकार stdClass की वस्तु का उपयोग नहीं कर सकते"

क्या मैं गलत कर रहा हूँ? यहाँ

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

और जगह मैं इसे कहते हैं कोशिश कर रहा हूँ है:

/** 
* 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 नाम की फ़ाइल है

$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 ज़रूर, यह करता है। मैं इसका उपयोग करता हूं क्योंकि मैं _think_ "गैर-php" प्रोग्रामर के लिए अधिक समझ में आता हूं। – Leri

+0

@PLB: इस फ़ंक्शन का उपयोग न्यूल ("अन्य" से - चेक के भाग से) लौटाता है। अभी भी "$ संसाधन-> क्वेरी-> प्रिंट" के साथ हो रहा है जैसे कि यह एक स्ट्रिंग के साथ एक स्केलर। –

संबंधित मुद्दे