Last updated on January 27th, 2022 at 12:30 pm

How would you differentiate if the call save() was to save a blogs or save comments? The solution was to use blog_save() or comment_save() before the introduction of classes in which we could write the save() function within the Blog class or the Comment class.Using classes is obviously a much more elegant solution.

Namespaces solves at least 2 problems, Name duplication while using multiple classes, functions etc., and an Alias.

Note: Namespace declaration statement has to be the very first statement or after any declare call in the script otherwise you may get 500 error and logs may say “PHP Fatal error

Using namespaces, we could simply separate the two functions with the same name very easily. We also have the code demo/example

<?php
namespace Blog;
function save()
{
echo "Saving the blog!<br>";
echo "I am inside blog.save<br>";
}

namespace Comment;
function save()
{
        echo "<br>Saving the comment!";
        echo "<br>I am inside comment.save";
}

// To invoke the functions
Blog.save();  // This prints - Saving the blog!
Comment.save(); // This prints - Saving the comment!
?>

Leave a Reply

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