A function can be added to a namespace in the following way
<?php
// example.php
namespace Example;
// Go with a known PHP function
function print_r() {
echo 'Does not do what the original function does';
}
?>
You would expect PHP to give an error for trying to define a
function that already exists in the global scope, but it
won't because of the NameSpace definition at the top. You
may be asking? What if I need to use the
print_r() function inside my definition?, well
there is a simple answer. You just have to tell the parser
you want the one inside the global scope. This can be done
by prefixing the function with the :: characters like this:
::print_r(). Here is an example code:
<?php
// example.php
namespace Example;
// Go with a known PHP function
function print_r() {
::print_r();
}
?>
Without the :: in front of it, it would cause an infinite
loop and the computer would run out of memory! So be careful
while programming like this.
Adding a Class
Since you should already know how to make classes, I'm not
going to go into much detail. Here is the code for a class
(added to our current code):
<?php
// example.php
namespace Example;
// Go with a known PHP function
function phpinfo() {
::phpinfo();
}
class test {
public $variable = 'String';
function __construct() {
echo 'test constructed<br />';
}
public function test_function() {
echo 'test_function() ran successfully<br />';
}
function __destruct() {
echo 'test destroyed<br />';
}
}
?>
As you can see this will define a simple class called test.
It contains the constructor, destructor and a function
called test_function().
Conclusion
As we have seen, PHP namespaces make working with the code
we have much more concise and unambiguous. Essesntially, we
create a namespace and use it to define anything we need
thereafter. It has been said that namespaces will redefine
PHP coding in general, and I am sure that will be the case.
However, more important to me is the fact that namespaces
provide us with a concise method of getting rid of ambiguity
in our code. I had one particular example where an
application used for different plugins that all used a class
named Database. That was before PHP 5.3 and my problem was
only resolvable by drastic measures. I wish I had the power
of namespaces at that time. Well now you do so USE IT!