PHP class not found when using namespace

后端 未结 2 1543
孤城傲影
孤城傲影 2020-12-16 02:53

I am new with this namespace thing.

I have 2 classes(separate files) in my base directory, say class1.php and class2.php inside a directory

相关标签:
2条回答
  • 2020-12-16 03:20

    You are going to need to implement an autoloader, as you have already read about it in SO.

    You could check the autoloading standard PSR-4 at http://www.php-fig.org/psr/psr-4/ and you can see a sample implementation of PSR-4 autoloading and an example class implementation to handle multiple namespaces here https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md.

    0 讨论(0)
  • 2020-12-16 03:27

    We can solve the namespace problem in two ways

    1) We can just use namespace and require

    2) We can use Composer and work with the autoloading!

    The First Way (Namespace and require) way

    Class1.php (Timer Class)

    namespace Utility;
    
    class Timer
       {
        public static function {}
       }
    

    Class2.php (Verification Class)

    namespace Utility;
    require "Class1.php";
    
    //Some interesting points to note down!
    //We are not using the keyword "use" 
    //We need to use the same namespace which is "Utility" 
    //Therefore, both Class1.php and Class2.php has "namespace Utility"
    
    //Require is usually the file path!
    //We do not mention the class name in the require " ";
    //What if the Class1.php file is in another folder?
    //Ex:"src/utility/Stopwatch/Class1.php"  
    
    //Then the require will be "Stopwatch/Class1.php"
    //Your namespace would be still "namespace Utility;" for Class1.php
    
    class Verification
       {
         Timer::somefunction();
       }
    

    The Second Way (Using Composer and the autoloading way)

    Make composer.json file. According to your example "src/Utility" We need to create a composer.json file before the src folder. Example: In a folder called myApp you will have composer.json file and a src folder.

       {
         "autoload": {
         "psr-4": {
            "Utility\\":"src/utility/"
            }
         }   
       }
    

    Now go to that folder open your terminal in the folder location where there is composer.json file. Now type in the terminal!

       composer dump-autoload
    

    This will create a vendor folder. Therefore if you have a folder named "MyApp" you will see vendor folder, src folder and a composer.json file

    Timer.php(Timer Class)

    namespace Utility;
    
    class Timer
         {
          public static function somefunction(){}
         }
    

    Verification.php (Verification Class)

    namespace Utility; 
    require "../../vendor/autoload.php"; 
    use Utility\Timer; 
    
    class Verification
      {
         Timer::somefunction(); 
      }
    

    This method is more powerful when you have a complex folder structure!!

    0 讨论(0)
提交回复
热议问题