php-namespace-tutorial-by-rasyue

PHP Namespace : Understanding PHP Namespace for Beginners

By Rasyue | On September 26, 2020

PHP Namespace is a feature in PHP that helps you to better organize your PHP Classes and Functions.

Within each php file, you can declare a Namespace and any Classes or Functions that you write within that particular file will belong to that Namespace

For example, in index.php

<?php
namespace Rasyue;

class Car{
  public $carName = "";
  public $carModel = "";

  function __construct($carName, $carModel) {
    $this->carName = $carName;
    $this->carModel = $carModel;
  }

  public function getCar() {
    echo "<p>Car Name :  {$this->carName }, Car Model:  {$this->carModel}</p>";
  }
}

?>

The above code shows a Class name Car that belong to the Namespace Rasyue.

Now if you want to instantiate the class Rasyue in another file with a different Namespace. You can do like so, create a new file and paste the code:

<?php
namespace Foo\Blog;
require 'index.php';

use Rasyue;

$car = new Rasyue\Car('Porsche', 'Cayenne S');
$car ->getCar();
?>

You might noticed the part, require 'index.php'. Yes, you still have to require the file. There is another way where you can autoload PHP Classes but we will discuss that in another post.

Why not just use require?

Now, some might think, if I have to require the file, what’s the point of declaring Namespaces, as long as I require the file, I will still be able to use it.

Well, you are NOT wrong. But think further and deeper, chances are right now you are working on a project or application that can be considered as small to medium size.

As time passed, you realized that your application gets bigger and more complex, your php files count increase and you end up with lots of Classes and Functions.

Now, how do you make sure that you won’t end up with problem having the same Class Name?

Using Namespace, you can avoid the problem having multiple classes with the same Class Name.

WAIT, if PHP Namespace only allows me to have multiple classes with the same name, what’s the point then?

Well, think of it this way, if you are able to organize your code in such a way that it results in you having cleaner and more maintainable code base, I do not see any reason why shouldn’t we go for it?

Leave a Reply

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

*

*
*