Attributes
Вернуться к: HTML_Common2
Attributes
HTML_Common2 class is intended as a parent class for classes representing HTML elements and its main purpose is to allow easy attribute handling for instances of these child classes.
Inividual attribute values can be set by HTML_Common2::setAttribute() and read by HTML_Common2::getAttribute() methods. Use HTML_Common2::removeAttribute() to remove an attribute, calling setAttribute() without explicitly giving a new attribute value serves a different purpose:
<?php
// these calls are identical
$html->setAttribute('checked');
$html->setAttribute('checked', 'checked');
?>
You can completely replace attributes of HTML_Common2 instance by using HTML_Common2::setAttributes() method and add/replace several new attributes at once by using HTML_Common2::mergeAttributes(). By default constructor of HTML_Common2 calls mergeAttributes(), so that some default attributes can be provided by a subclass and only overridden if needed. Note that both of the above methods can accept either a string of HTML attributes or an array of these.
Finally, HTML_Common2::getAttributes() method returns the values of all the instance's attributes. Those can be returned either as an associative array or a string. As the package is intended for XHTML-compliant output, attribute names will always be lowercased and quotes will be used around attribute values when outputting the attribute string.
Working with CSS Classes
HTML_Common2 contains several methods to easily handle 'class' attribute of HTML tags: HTML_Common2::addClass(), HTML_Common2::removeClass() and HTML_Common2::hasClass(). Their behaviour should be easily deducable from their names:
<?php
$html->setAttribute('class', 'foo bar');
$html->removeClass('foo');
if (!$html->hasClass('foo')) {
$html->addClass('notFoo');
}
echo $html->getAttribute('class');
?>
will output
bar notFoo
Usage Example
The following example shows a somewhat minimal subclass of HTML_Common2 and possible ways to change its attributes.
Methods available for attribute handling
<?php
// a non-abstract subclass of HTML_Common2
class HTML_Tag_Foo extends HTML_Common2
{
// some predefined attributes, won't be overwritten
protected $attributes = array('class' => 'pretty');
// basic implementation of magic __toString() method
public function __toString()
{
return '<foo' . $this->getAttributes(true) . ' />';
}
}
$foo = new HTML_Tag_Foo(array('size' => 'small', 'align' => 'top left corner',
'foo' => 'foo value'));
// note how the attributes from this string will be handled
$foo->mergeAttributes("bar LEVEL=0 value='Whatever'");
$foo->removeAttribute('align');
$foo->setAttribute('size', 'smaller');
echo $foo;
?>
The above code will output:
<foo class="pretty" size="smaller" foo="foo value" bar="bar" level="0" value="Whatever" />
Вернуться к: HTML_Common2