PHP – namespace

Namespace‘ing is a great way of splitting functions / classes into different spaces that could have the same name but do not cause issues. This is great if you are trying to combine different projects together that many have the same function names and you want to call different projects code functions without having to worry that you are calling the wrong function.

For example if you have a file called codingfriends.php

<?php
namespace codingfriends;
 
function sayHello()
{
    echo "Say hello from codingfriends.";    
}
 
function sayHelloFromSub()
{
    echo sub\sayHello();
}
?>

and another file called codingfriendssub.php

<?php
namespace codingfriends\sub;
 
function sayHello()
{
    echo "Say hello from codingfriends sub module";    
}
?>

and then have the index.php file

 
<?
include "codingfriends.php";
include "codingfriends.sub.php";
 
echo codingfriends\sayHello()."<br/>"; // calling the codingfriends namespace
echo codingfriends\sub\sayHello()."<br/>"; // call the codingfriends sub namespace
echo codingfriends\sayHelloFromSub()."<br/>"; // calling the sub namespace quicker.
?>

then the first two lines include the two different name spaces and you are able to call the same function names without having to worry that you are calling the wrong function.

echo codingfriends\sayHello()."<br/>"; // calling the codingfriends namespace

will call the sayHello() from within the namespace codingfriends

echo codingfriends\sub\sayHello()."<br/>"; // call the codingfriends sub namespace

will call the namespace codingfriendssub sayHello function and the best thing is is if you are within a namespace and want to call a sub namespace within your namespace (it is like a tree with roots) you are able to do

    echo sub\sayHello();

from within the namespace codingfriends, it will find the codingfriends\sub namespace and then call the sayHello() function within that namespace.

The output would be for the index.php file

Say hello from codingfriends.
Say hello from codingfriends sub module
Say hello from codingfriends sub module

Leave a Reply

Your email address will not be published. Required fields are marked *