PHP import classes with use keywords

前端 未结 1 1100
遇见更好的自我
遇见更好的自我 2021-01-29 13:21

I don\'t use so far PHP use word, but must now... :)

index.php content:

require_once \'Classes/MainClass.php\';
$obj = new         


        
相关标签:
1条回答
  • 2021-01-29 14:01

    As per comment from @deceze, you will either need to explicitly import the additional class, using a require statement, or autoload.

    The use statement is for aliasing a class, and as @deceze said, can be used to pull in a class from a different namespace, or to avoid a class conflict.

    Having a class called 'Main' may not be ideal. Is it a singleton, or will there be multiple 'Main's?
    Maybe this class would be better named 'App'.

    In the longer term you will want to learn about using namespaces, so that if you use other people's classes and plugins, you won't have conflict. I've added a solution, and also some broader info below.

    To get you off the hook:

    Classes/MainClass.php

    <?php
    
    require_once 'Classes/AdminFrontEnd.php';
    
    class Main {   /*   etc...  */ 
    


    Further reading I would recommend:

    Examples for creating an autoload:

    http://php.net/manual/en/language.oop5.autoload.php

    You'll probably want to learn about namespaces too:

    http://php.net/manual/en/language.namespaces.php

    I also highly recommend reading about interoperability coding standards. It's a lot to take in to begin with, but it will help you understand the logic behind using namespaces, and autoloaders.

    http://www.php-fig.org/

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