MisterPi MisterPi - 26 days ago 7
PHP Question

How to use namespace and use in PHP?

I have file

index.php
in directory
Main
;

There are also directory
Helpers
inside
Main
with class
Helper
.

I tried to inject class
Helpers\Helper
in
index.php
as:

<?

namespace Program;

use Helpers\Helper;


class Index {

public function __construct()
{
$class = new Helper();
}

}


But it does not work.

How to use namespace and use in PHP?

Answer

With Your Description, Your Directory Structure should look something similar to this:

    Main*
        -- Index.php
        |
        Helpers*
               --Helper.php

If You are going by the book with regards to PSR-4 Standards, Your Class definitions could look similar to the ones shown below:

Index.php

    <?php
        // FILE-NAME: Index.php.
        // LOCATED INSIDE THE "Main" DIRECTORY
        // WHICH IS PRESUMED TO BE AT THE ROOT OF YOUR APP. DIRECTORY


        namespace Main;            //<== NOTICE Main HERE AS THE NAMESPACE...

        use Main\Helpers\Helper;   //<== IMPORT THE Helper CLASS FOR USE HERE   

        class Index {

            public function __construct(){
                $class = new Helper();
            }

        }

Helper.php

    <?php
        // FILE NAME Helper.php.
        // LOCATED INSIDE THE "Main/Helpers" DIRECTORY


        namespace Main\Helpers;     //<== NOTICE Main\Helpers HERE AS THE NAMESPACE...


        class Helper {

            public function __construct(){
                // SOME INITIALISATION CODE
            }

        }