Much like directories in a file system, namespaces are a way to group items in an orderly manner. In this way they are used to avoid collisions. In addition, namespaces can be used to shorten long names in order to increase a code’s readability. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Will print out:
this is my function 1
this is my function 2
Note that without the starting slash \ in the first call to myfunction() would have failed because PHP would have considered the function to be undefined.
Namespaces in XML
Namespaces can be used in XML documents with the same purposes in mind: to eliminate naming collisions and to shorten names for readability. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
SimpleXML and Namespaces
SimpleXML knows how to use namespaces. For example, given the following code:
1 2 3 4 5 6 7 |
|
Prints the following output:
=> http://cars.org/fleet
mk => http://cars.org/make
mo => http://cars.org/model
vn => http://cars.org/vin
DOM and Namespaces
Alone, DOM’s namespace functionality is limited. Its real power comes into its own when used with XPath. For example:
1 2 3 4 5 6 7 8 9 10 11 |
|
Prints the following output:
/Users/john/src/php/cars.xml
http://www.w3.org/XML/1998/namespace
http://cars.org/vin
http://cars.org/model
http://cars.org/make
http://cars.org/fleet