Friday, April 20, 2012

what is the difference between foo(array(...)) and foo($x=array(...))?

See this example:



This class extends DOMElement. Every DOMElement must be a part of
any DOMDocuement to be modifable.



class Xmlrize  extends DOMElement
{
private static $dom;

public function __construct(/*. string .*/ $name,$value =null) {
parent::__construct($name,$value,null);
if(!self::$dom) {
self::$dom = new DOMDocument('1.0','UTF-8');
}
self::$dom->appendChild($this);
}
}


Used to add array into DOM. If value of the array is not Xmlrize, then I ignore it.



class Attributes extends Xmlrize {

public function __construct(array $attributes)
{
parent::__construct('Attributes');

foreach($attributes as $name => $value) {
$element = new Xmlrize($name);
if($value instanceof Xmlrize)
$element->appendChild($value);
$this->appendChild($element);
}
}
}


You can add any DOMNode to the constructor. In my example
it will be instance of Xmlrize



class Html extends Xmlrize {

public function __construct(DOMNode $obj = null) {
parent::__construct('html');
if(!is_null($obj)) {
if($obj instanceof Attributes)
$this->addAttributes($obj);
else
$this->appendChild($obj);
}
}


This method shows if attribute is or is not instance of Xmlrize.



    protected function addAttributes(Attributes $attributes)
{
$remove =array();
foreach($attributes->childNodes as $attribut) {
if($attribut->childNodes->length == 1) {
$item = $attribut->childNodes->item(0);
echo $attribut->nodeName.': ';
echo $item->nodeName.' has value '.$item->nodeValue.'. ';
echo 'Is it DomElement? ';
echo ($item instanceof DomElement) ? 'true' : 'false';
echo '. Is it Xmlrize? ';
echo ($item instanceof Xmlrize) ? 'true' : 'false';
echo '.'.PHP_EOL;
}
}
return null;
}
}


Example of initiating of Attributes by array. See the differences!



/* works as expected */
$like = new Html(new Attributes(
$xx = array('XXX'=> new Xmlrize('foo', 'baar'))
));

/* do not work as exptected */
$like = new Html(new Attributes(
array('XXX'=> new Xmlrize('foo', 'baar'))
));
?>


The example above returns:



XXX: foo has value baar. Is it DomElement? true. Is it Xmlrize? true.
XXX: foo has value baar. Is it DomElement? true. Is it Xmlrize? false.


Why if I add '$xx =' the element is considered as Xmlrize and if not, it isn't?





No comments:

Post a Comment