namespaces in PHP OOPS

 <?php


// NOTE: Namespace declaration statement has to be the very first statement or after any declare call in the script
// No code may exist outside of namespace {}

namespace abc {
    class xyz {}
}

namespace def {
    class xyz
    {
        public function __construct()
        {
            echo "XYZ from DEF namespace";
        }
    }
}
//If there is no Name present for namespace then it will consider as "Global namespace" as shown below:
namespace {
    class xyz
    {
        public function __construct()
        {
            echo "XYZ from Global namespace";
        }
    }
    $obj = new xyz();
    echo "<br><br>";
    $objTwo = new def\xyz();    //First way for making Object of namespace def => class xyz
    echo "<br><br>";

    use def\xyz as defXyz;      //Second way for making Object of namespace def => class xyz
    $objThree = new defXyz();
}

//There can be subnamespaces in namespace as shown below:
//Here below, "defTwo" is namespace and "ghi","jkl" is subnamespaces
namespace defTwo\ghi\jkl {
}

//We can declare namespace as shown below, class "pqr" will be consider of namespace "defThree"
// namespace defThree;
// class pqr
// {
//     public function message()
//     {
//         echo "Hello this is the method 'message' and class 'pqr' and they both is considered of namespace 'defThree'";
//     }
// }
// $obj = new pqr();
// $obj->message();


Comments

Popular posts from this blog

GROUP BY Clause and HAVING Clause in PHP

Method Overriding in Traits in PHP

Mysqli database Connection and Display Table Data from Database