Change your code as shown below
$build->addElement('input');
$build->addAttr('type','text');
instead of
$attr->addElement('input');
$attr->addAttr('type','text');
Thanks
Pregunta
I hope somebody can help me, i am oop starter and the script below gives output <
but i want this <input type="text">
.
Now i created a Build class but it doesnt work. What do i do wrong and how can i fix this?
Can somebody help me?
Thnks!
//set get Element
class Element {
private $_element;
function addElement($element) {
$this->_element = $element;
}
function getElement(){
return $this->_element;
}
}
//add and set Atrr
class attrType extends Element {
//set var
public $_attrType;
function __construct(){
$this->_attrType = array();
}
function addAttr($attrType, $attrValue){
$this->_attrType[$attrType] = $attrValue;
}
function getAttr(){
return $this->_attrType;
}
}
//build input text field
class Build extends attrType {
function Builder() {
$html .= "<";
$html .= ''.$this->getElement();
foreach( $this->getAttr() as $key => $value){
$html .= " $key=";
$html .= "\"$value\">";
}
return $html;
}
}
$element = new Element();
$attr = new attrType();
$build = new Build();
$attr->addElement('input');
$attr->addAttr('type','text');
echo $build->Builder();
Solución 2
Change your code as shown below
$build->addElement('input');
$build->addAttr('type','text');
instead of
$attr->addElement('input');
$attr->addAttr('type','text');
Thanks
Otros consejos
You are creating separate objects and expecting them to share properties, that's the problem. If you change your last 3 lines to this, your code will work:
$build->addElement('input');
$build->addAttr('type','text');
echo $build->Builder();
Although the code works, IMO it's not the best way to do it. When inheriting, a good rule of thumb is to to ask yourself: can the derived class be considered the class that it derives from? In other words is a Builder
an Element
, I don't think it is. For me a Builder
would take an element and build the HTML and so I wouldn't derive Builder
from Element
.
A good example of inheritance in this case would be to have your base Element
class, then derive specific elements from it such as TextInput
, TextArea
, RadioButton
. Each of those can be considered an Element
, and therefore would be a good choice for inheritance.
Be careful not to overcomplicate things too much, OOP doesn't mean make it difficult. What are the benefits to a Builder class? If you can't name any then just use a build()
or toHTML()
method on the parent class.