【发布时间】:2012-12-03 16:07:52
【问题描述】:
所以我写了一个基本类,我已经扩展它来创建 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;
那么问题出在哪里?
回显 $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 类,我将发布它,但所有此类都是您扩展以创建元素的基类。唯一需要的就是一组选项。
【问题讨论】:
-
不是解决方案...但是为什么在你的 foreach 中使用
return()?这只会在第一次迭代时杀死 foreach。 -
哦,这可能是我的错,它应该在 foreach 之外 >.
-
它返回了一个对象,因为您将
$element设置为AisisCode_Form_Elements_Input类的一个新实例。如果您希望能够从对象变量中回显字符串,则需要使用魔术__toString方法。我错过了什么吗? -
我以前从未听说过......你确定吗?我现在正在查看 __toString 文档
-
@KyleAdams,查看此链接:php.net/manual/en/language.oop5.magic.php#object.tostring