php-namespaces

PHP & Laravel NameSpaces and Traits-01

Ashwani Garg
2 min readFeb 11, 2020

As we all know, namespaces and traits are not new in PHP, but still many php developers don’t use these Great concepts because of their complexity.

So, in this post. I’ll try to clear them with examples.

What are namespace and traits?

How you can implement them in your code to make your code reusable and extensible?

Benefits of namespaces

  1. You can use namespace to avoid name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Namespaces also have the ability to alias (or shorten) Extra_Long_Names designed to reduce the first problem, improving readability of source code.

Let’s understand namespaces with an example.

create a folder name “php_oops” in htdocs(xampp) or www (xwamp)

create a new folder under root directory named “namespaces”, & then create a file index.php under namespaces folder.

namespaces/index.php

now let’s create a new file under “namespaces/long_name_folder” named first.php

namespaces/long_name_folder/first.php

now include the first.php in index.php file. and to use first’s classes and methods, we have to use it’s namespace in the index.php, and you have to write the below code to import first’s namespace in the index file.

To use the namespace in PHP, use something like this at the top of your file.

include (‘./long_name_folder/first.php’);

use \long_name_folder\first\A as fA ;

Syntax:

use \path_to_file\className as short_name;

and after that, now you can create object of class A from first namespace.

$object = new fA;

index.php

I hope, namespaces are little bit clear to you now. Don’t worry about if you still have any confusion, I’ll also write some namespace examples with Laravel.

Now, let’s move to traits

--

--

Ashwani Garg
Ashwani Garg

Written by Ashwani Garg

FullStack Web, App Developer and also Full Time Blogger

No responses yet