2012-12-03 87 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必须返回一个字符串。

祝你好运。

相关问题