Wednesday, 10 January 2018

PHP namespace example - Tutorial

PHP namespace example - Tutorial

Question: What is namespace in PHP?
namespace is reserve keywords which is used to encapsulating the class, method, data member variables and static methods.


Question: Benefits of namespace in PHP?
  1. Encapsulate the data which fixed collisions between code you create, and internal PHP classes/functions/constants.
  2. Ability to alias which improved the readability of source code.



Question: From which version php support namespaces?
PHP5.3



Question: How namespaces are defined?
namespaces are defined with keyword namespace
For Example:
namespace math



Question: Example - Simple class without namespace (OR Global namespace)?
File: /myproject/simple-file.php
class mathSimple {

    function add($a, $b) {
        return $a + $b;
    }

}

File: /myproject/run-example.php
include "simple-file.php";

$obj1 = new mathSimple(); //calling for Global Namespace
echo $obj1->add(10,20);//30

When we execute run-example.php file, it will return 30


Question: Example - Simple class with namespace?
File: /myproject/namespace-file.php
namespace math;

class mathSimple {

    function add() {        
        return array_sum(func_get_args()) ;
    }

}

File: /myproject/run-example.php
namespace math;
include "simple-file.php";
include "namespace-file.php";


$obj1 = new \mathSimple(); //calling for Global Namespace
echo $obj1->add(10,20,30);

echo "\n";
$obj2 = new mathSimple(); //calling for namespace math
echo $obj2->add(10,20,30);
Question: How to import namespaces?
use Zend\View\Model\ViewModel;



Question: How to use alias namespaces for import namespace?
use Zend\View\Model\ViewModel as ZendViewModel;



Question: Can we override the php in-built using namespace? Yes, We can do. File: /myproject/namespace-file2.php
namespace math;

class mathSimple {

    function add() {        
        return array_sum(func_get_args()) ;
    }

}
function strlen($string){
    return 'in built functi';
}


File: /myproject/run-example2.php
namespace math;
include "namespace-file2.php";

echo strlen('string'); //calling namespace function
echo \strlen('strlen'); //calling inbuilt function