4

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?

3
  • 1
    But it does not work. How exactly? Commented Nov 13, 2016 at 8:27
  • Phpstorms highlights as red this use Commented Nov 13, 2016 at 8:33
  • Undefined namespace Helpers Commented Nov 13, 2016 at 8:33

1 Answer 1

2

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   

        // 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
            }

        }
Sign up to request clarification or add additional context in comments.

7 Comments

I still get error: Class 'Main\Helpers\Helper' not found in in index.php
May be I should use include() above before namespace?
@MisterPi You have to find a Way to either autoload the class or simply require it manually using either require or include.... the Post was updated to reflect that....
@MisterPi Just at: require_once __DIR__ . "/helpers/Helper.php"; at the top of your Index.php File.... just after the namespace declaration....
For what then I need to use use if I do require_once anyway?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.