简体   繁体   English

PHP导入类和use关键字

[英]PHP import classes with use keywords

I don't use so far PHP use word, but must now... :) 我到目前为止还没有使用PHP use word,但是现在必须use ... :)

index.php content: index.php内容:

require_once 'Classes/MainClass.php';
$obj = new Main();
echo $obj->test();

Classes/MainClass.php 类/MainClass.php

<?php
use AdminFrontEnd;

class Main {
    function test(){
        return new AdminFrontEnd("debug");
    }
} 

AdminFrontEndClass.php content: AdminFrontEndClass.php内容:

<?php
class AdminFrontEnd {
    function __constuctor($test){
        echo $test;
    }
} 

and final, following error: 最后,以下错误:

Fatal error: Class 'AdminFrontEnd' not found in Classes/MainClass.php on line 10 致命错误:在第10行的Classes / MainClass.php中找不到类'AdminFrontEnd'

As per comment from @deceze, you will either need to explicitly import the additional class, using a require statement, or autoload. 根据@deceze的注释,您将需要使用require语句显式导入其他类,或者自动加载。

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. use语句用于别名一个类,正如@deceze所说,可用于从另一个名称空间提取一个类,或避免类冲突。

Having a class called 'Main' may not be ideal. 拥有一个名为“ Main”的类可能不是理想的选择。 Is it a singleton, or will there be multiple 'Main's? 是单身,还是会有多个“主要”?
Maybe this class would be better named 'App'. 也许最好将此类命名为“ 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 类/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 http://php.net/manual/zh/language.oop5.autoload.php

You'll probably want to learn about namespaces too: 您可能还想了解名称空间:

http://php.net/manual/en/language.namespaces.php http://php.net/manual/zh/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/ http://www.php-fig.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM