2012-12-03 86 views
0

所以我寫了一個基本的類,我已經擴展到創建html元素。基於Zend - 不僅如此。 沒有這不是關於或相對於問題的Zend當我得到一個字符串時返回一個對象

class AisisCore_Form_Elements_Input extends AisisCore_Form_Element { 

    protected $_html = ''; 

    public function init(){ 

     foreach($this->_options as $options){ 
      $this->_html .= '<input type="text" '; 

      if(isset($options['id'])){ 
       $this->_html .= 'id="'.$options['id'].'" '; 
      } 

      if(isset($options['class'])){ 
       $this->_html .= 'class="'.$options['class'].'" '; 
      } 

      if(isset($options['attributes'])){ 
       foreach($options['attributes'] as $attrib){ 
        $this->_html .= $attrib; 
       } 
      } 

      $this->_html .= $this->_disabled; 
      $this->_html .= ' />'; 

      return $this->_html; 
     } 
    } 
} 

所以這類擴展它由一個構造函數中的選項的陣列,基本元件被設置爲這樣的我的元素類:

$array_attrib = array(
    'attributes' => array(
     'placeholder' => 'Test' 
    ) 
); 

$element = new AisisCore_Form_Elements_Input($array_attrib); 
echo $element; 

那麼是什麼問題?

呼應$元素對象給我一個錯誤說它不能將對象轉換爲字符串,因此當我的var_dump它,我得到這個回:

object(AisisCore_Form_Elements_Input)#21 (3) { 
    ["_html":protected]=> 
    string(22) "<input type="text" />" 
    ["_options":protected]=> 
    array(1) { 
    ["attributes"]=> 
    array(1) { 
     ["placeholder"]=> 
     string(4) "Test" 
    } 
    } 
    ["_disabled":protected]=> 
    NULL 
} 

一些人能解釋這是怎麼回事?最後,我檢查了我是在迴應一個字符串而不是對象。我是如何設法創建一個對象的?

如果您需要查看AisisCore_Form_Element類,我會發布它,所有這個類都是您擴展來創建元素的基類。它唯一需要的是一系列選項。

+0

不是解決方案......但爲什麼你的foreach中的return()?這將在第一次迭代中殺死foreach。 –

+0

哦,這可能是我的錯,它應該在foreach>。<清晨編碼 – TheWebs

+1

它給你回一個對象,因爲你將'$ element'設置爲'AisisCode_Form_Elements_Input'類的新實例。如果你想能夠從一個對象變量中回顯一個字符串,你需要使用神奇的'__toString'方法。我錯過了什麼嗎? –

回答

0

看起來像你的構造函數試圖返回的值(在for循環中間的爲好),當你可能想是這樣的....

class AisisCore_Form_Elements_Input extends AisisCore_Form_Element { 

    protected $_html = ''; 

    public function init(){ 

     foreach($this->_options as $options){ 
      $this->_html .= '<input type="text" '; 

      if(isset($options['id'])){ 
       $this->_html .= 'id="'.$options['id'].'" '; 
      } 

      if(isset($options['class'])){ 
       $this->_html .= 'class="'.$options['class'].'" '; 
      } 

      if(isset($options['attributes'])){ 
       foreach($options['attributes'] as $attrib){ 
        $this->_html .= $attrib; 
       } 
      } 

      $this->_html .= $this->_disabled; 
      $this->_html .= ' />'; 

      // Constructors Don't Return Values - this is wrong 
      //return $this->_html; 
     } 
    } 

    // provide a getter for the HTML 
    public function getHtml() 
    { 
     return $this->_html; 
    } 
} 

現在你的例子可以更新看起來像這樣...

$element = new AisisCore_Form_Elements_Input($array_attrib); 
echo $element->getHtml(); 
1

您試圖回顯一個實例,而不是一個字符串。 你甚至var_dumped它,並清楚地看到,這是一個對象..不是一個字符串。

如果您希望您能夠將實例用作字符串,則必須在您的類中實現__toString 方法。

請注意,方法__toString必須返回一個字符串。

祝你好運。

相關問題