0

所以我写了一个基本类,我已经扩展它来创建 html 元素。基于 Zend - 但不完全是。不,这不是关于 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;

所以有什么问题?

回显 $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 类,我将发布它,但所有此类都是您扩展以创建元素的基类。唯一需要的是一系列选项。

4

2 回答 2

1

您正在尝试回显一个实例,而不是一个字符串。您甚至 var_dumped 并清楚地看到这是一个对象.. 不是字符串。

如果您希望能够将实例用作字符串,则必须在类中实现 __toString 方法。

请注意,方法 __toString 必须返回一个字符串。

祝你好运。

于 2012-12-03T16:42:11.613 回答
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();
于 2012-12-03T16:51:15.203 回答