How to use namespace and use them in PHP?

I have a file index.phpin a directory Main;

There is also a directory Helpersinside Mainwith the class Helper.

I tried to introduce a class Helpers\Helperin index.phplike:

<?

namespace Program;

use Helpers\Helper;


class Index {

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

}

But that will not work.

How to use namespace and use in PHP?

+4
source share
1 answer

With your description, your directory structure should look something like this:

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

If you are reading a book regarding PSR-4 standards , your class definitions may look like the following:

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   

        // IF YOU ARE NOT USING ANY AUTO-LOADING MECHANISM, YOU MAY HAVE TO 
        // MANUALLY IMPORT THE "Helper" CLASS USING EITHER include OR require
        require_once __DIR__ . "/helpers/Helper.php";

        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
            }

        }
+2
source

Source: https://habr.com/ru/post/1660615/


All Articles