note 109154 added to book.simplexml
| From: | LaurentVervisch | Date: | Sun, 24 Jun 2012 10:57:22 +0000 |
| Subject: | note 109154 added to book.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188773@lists.php.net to get a copy of this message | ||
Here is an example of an easy mapping between xml and classes defined by user.
<?php
class XmlClass extends SimpleXMLElement
{
/**
* Returns this object as an instance of the given class.
*/
public function asInstanceOf($class_name)
{
// should check that class_name is valid
return simplexml_import_dom(dom_import_simplexml($this), $class_name);
}
public function __call($name, array $arguments)
{
echo "magic __call called for method $name on instance of
".get_class()."\n";
// class could be mapped according $this->getName()
$class_name = 'Test';
$instance = $this->asInstanceOf($class_name);
return call_user_func_array(array($instance, $name), $arguments);
}
}
class Test extends XmlClass
{
public function setValue($string)
{
$this->{0} = $string;
}
}
$xml = new XmlClass('<example><test/></example>');
$test = $xml->test->asInstanceOf('Test');
echo get_class($xml->test), "\n";
echo get_class($test), "\n";
$test->setValue('value set directly by instance of Test');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";
$xml->test->setValue('value set by instance of XmlClass and magic __call');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";
?>
XmlClass
Test
value set directly by instance of Test
value set directly by instance of Test
magic __call called for method setValue on instance of XmlClass
value set by instance of XmlClass and magic __call
value set by instance of XmlClass and magic __call
----
Server IP: 69.147.83.197
Probable Submitter: 90.17.219.181
----
Manual Page -- http://www.php.net/manual/en/book.simplexml.php
Edit -- https://master.php.net/note/edit/109154
Del: integrated -- https://master.php.net/note/delete/109154/integrated
Del: useless -- https://master.php.net/note/delete/109154/useless
Del: bad code -- https://master.php.net/note/delete/109154/bad+code
Del: spam -- https://master.php.net/note/delete/109154/spam
Del: non-english -- https://master.php.net/note/delete/109154/non-english
Del: in docs -- https://master.php.net/note/delete/109154/in+docs
Del: other reasons-- https://master.php.net/note/delete/109154
Reject -- https://master.php.net/note/reject/109154
Search -- https://master.php.net/manage/user-notes.php