Importing a namespace vs. including files in PHP

前端 未结 1 570
执笔经年
执笔经年 2021-02-19 18:21

I have started building my code library since PHP 4. I have used require_once to import classes. Now with PHP 5.3 I have met defining namespaces and importing them.

1条回答
  •  [愿得一人]
    2021-02-19 19:15

    use and require_once are completely different things. use is not doing any file importing at all. use is just making your life easier. Instead of writing Full\Path\To\Class every time, you can do

    use Full\Path\To\Class
    
    $bar = new Class();
    

    Your are still responsible to include the right files.

    Instead of loading all the files by hand, you could rely on PHP auto class loading.

    You can use Composer or Frameworks like Symfony 2 or Zend2 which are handling all the autoloading stuff for you.

    Migrating existing code to use autoloading and use statements instead of include_once may be very time consuming. There's most likely no search and replace solution.

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