Monday, 7 June 2021

php: namespaces

Namespaces are used to

a.   Organize your code

b.   Solve naming conflict problems. For example, while developing an application, you may use some external libraries, there is a chance that multiple classes with same name. Using name spaces, we can avoid this name conflicts.

 

How to create a namespace?

Syntax

namespace namespace_name;

 

Let’s see it with an example.

 

arithmetic_utils_1.php

<?php

namespace nominal;

function area_of_circle($radius){
    return 3.14 * $radius;
}

?>

 

arithmetic_utils_2.php

<?php

namespace accurate;

function area_of_circle($radius){
    return 3.14285714 * $radius;
}

?>

As you see above snippets, I defined two namespaces.

a.   nominal

b.   accurate

 

Both the namespaces has ‘area_of_circle’ methods.

 

How to access the method defined in particular namespace?

Syntax

namespace_name\method_name(arguments);

 

Example

$area_of_circle_1 = nominal\area_of_circle($radius);

 

namespace_demo.php

#!/usr/bin/php

<?php
   include 'arithmetic_utils_1.php';
   include 'arithmetic_utils_2.php';

   $radius = 12.34;

   $area_of_circle_1 = nominal\area_of_circle($radius);
   $area_of_circle_2 = accurate\area_of_circle($radius);

   echo "for the radius $radius\n";
   echo "area_of_circle_1 : $area_of_circle_1\n";
   echo "area_of_circle_2 : $area_of_circle_2\n";

?>


Output

$./namespace_demo.php 

for the radius 12.34
area_of_circle_1 : 38.7476
area_of_circle_2 : 38.7828571076




 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment