关键字“use”在 PHP 中是如何工作的,我可以用它导入类吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10965454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does the keyword "use" work in PHP and can I import classes with it?
提问by Green
I have a file with a class Resp. The path is:
我有一个类的文件Resp。路径是:
C:\xampp\htdocs\One\Classes\Resp.php
And I have an index.phpfile in this directory:
我index.php在这个目录中有一个文件:
C:\xampp\htdocs\Two\Http\index.php
In this index.phpfile I want to instantiate a class Resp.
在这个index.php文件中,我想实例化一个类Resp。
$a = new Resp();
I know I can use requireor includekeywords to include the file with a class:
我知道我可以使用requireorinclude关键字将文件包含在一个类中:
require("One\Classes\Resp.php"); // I've set the include_path correctly already ";C:\xampp\htdocs". It works.
$a = new Resp();
But I want to import classes without using requireor include. I'm trying to understand how usekeyword works. I tried theses steps but nothing works:
但我想在不使用require或的情况下导入类include。我试图了解use关键字的工作原理。我尝试了这些步骤,但没有任何效果:
use One\Classes\Resp;
use xampp\htdocs\One\Classes\Resp;
use htdocs\One\Classes\Resp;
use One\Classes;
use htdocs\One\Classes; /* nothing works */
$a = new Resp();
It says:
它说:
Fatal error: Class 'One\Classes\Resp' not found in C:\xampp\htdocs\Two\Http\index.php
How does the keyword usework? Can I use it to import classes?
关键字是如何use工作的?我可以用它来导入类吗?
采纳答案by zerkms
usedoesn't include anything. It just imports the specified namespace (or class) to the current scope
use不包括任何东西。它只是将指定的命名空间(或类)导入到当前作用域
If you want the classes to be autoloaded - read about autoloading
如果您希望自动加载类 - 阅读有关自动加载的信息
回答by Rajan Rawal
No, you can not import a class with the usekeyword. You have to use include/requirestatement. Even if you use a PHP auto loader, still autoloader will have to use either includeor requireinternally.
不,您不能使用use关键字导入类。你必须使用include/require语句。即使您使用 PHP 自动加载器,自动加载器仍然必须使用include或在require内部使用。
The Purpose of usekeyword:
使用关键字的目的:
Consider a case where you have two classes with the same name; you'll find it strange, but when you are working with a big MVC structure, it happens. So if you have two classes with the same name, put them in different namespaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the usestatement so that it can make a decision which one is going to be used on.
考虑一个例子,你有两个同名的类;您会发现它很奇怪,但是当您使用大型 MVC 结构时,它就会发生。因此,如果您有两个同名的类,请将它们放在不同的命名空间中。现在考虑您的自动加载器何时加载两个类(由require),并且您将要使用类的对象。在这种情况下,编译器会混淆在两个类对象中加载哪个类对象。为了帮助编译器做出决定,您可以使用该use语句,以便它可以决定将使用哪个语句。
Nowadays major frameworks do use includeor requirevia composerand psr
现在主要的框架确实使用include或require通过composer和psr
1) composer
1)作曲家
2) PSR-4autoloader
2) PSR-4自动装弹机
Going through them may help you further.
You can also use an alias to address an exact class. Suppose you've got two classes with the same name, say Mailerwith two different namespaces:
通过它们可能会进一步帮助您。您还可以使用别名来寻址确切的类。假设你有两个同名的类,比如Mailer有两个不同的命名空间:
namespace SMTP;
class Mailer{}
and
和
namespace Mailgun;
class Mailer{}
And if you want to use both Mailer classes at the same time then you can use an alias.
如果您想同时使用两个 Mailer 类,那么您可以使用别名。
use SMTP\Mailer as SMTPMailer;
use Mailgun\Mailer as MailgunMailer;
Later in your code if you want to access those class objects then you can do the following:
稍后在您的代码中,如果您想访问这些类对象,则可以执行以下操作:
$smtp_mailer = new SMTPMailer;
$mailgun_mailer = new MailgunMailer;
It will reference the original class.
它将引用原始类。
Some may get confused that then of there are not Similar class names then there is no use of usekeyword. Well, you can use __autoload($class)function which will be called automatically when usestatement gets executed with the class to be used as an argument and this can help you to load the class at run-time on the fly as and when needed.
有些人可能会感到困惑,如果没有相似的类名,那么就没有使用use关键字。好吧,您可以使用__autoload($class)将在use语句执行时自动调用的函数,并将类用作参数,这可以帮助您在运行时根据需要即时加载类。
Refer this answerto know more about class autoloader.
请参阅此答案以了解有关类自动加载器的更多信息。
回答by Lukas Lukac
Don't overthink what a Namespaceis.
不要过度考虑命名空间是什么。
Namespaceis basically just a Classprefix (like directory in Operating System) to ensure the Classpath uniqueness.
命名空间基本上只是一个类前缀(如操作系统中的目录),以确保类路径的唯一性。
Also just to make things clear, the usestatement is not doing anything only aliasing your Namespacesso you can use shortcuts or include Classeswith the same name but different Namespacein the same file.
同样为了清楚起见,use语句并没有做任何事情,只是为您的命名空间设置别名,因此您可以使用快捷方式或在同一文件中包含具有相同名称但不同命名空间的类。
E.g:
例如:
// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;
if ($_SERVER['APP_DEBUG']) {
// So you can utilize the Debug class it in an elegant way
Debug::enable();
// Instead of this ugly one
// \Symfony\Component\Debug\Debug::enable();
}
If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
如果您想了解 PHP 命名空间和自动加载(Composer 的旧方式和新方式)是如何工作的,您可以阅读我刚刚写的关于此主题的博客文章:https: //enterprise-level-php.com/ 2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
回答by Samy Dindane
You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the samefile though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)
无论如何,您必须包含/要求该类,否则 PHP 将不知道名称空间。
不过,您不必在同一个文件中执行此操作。例如,您可以在引导文件中执行此操作。(或使用自动加载器,但这实际上不是主题)
回答by Tyler Carter
The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.
问题很可能是您需要使用自动加载器,该加载器将采用类的名称(在本例中以“\”分隔)并将其映射到目录结构。
You can check out this article on the autoloadingfunctionality of PHP. There are many implementations of this type of functionality in frameworks already.
您可以查看这篇关于PHP自动加载功能的文章。框架中已经有许多此类功能的实现。
I've actually implemented one before. Here's a link.
我之前实际上已经实现了一个。这是一个链接。
回答by Eric Draven
I agree with Green, Symfony needs namespace, so why not use them ?
我同意 Green,Symfony 需要命名空间,那么为什么不使用它们呢?
This is how an example controller class starts:
这是示例控制器类的启动方式:
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class WelcomeController extends Controller { ... }
命名空间 Acme\DemoBundle\Controller;
使用 Symfony\Bundle\FrameworkBundle\Controller\Controller;
class WelcomeController 扩展 Controller { ... }
回答by Abdul Mannan
The usekeyword is for aliasing in PHP and it does not import the classes. This really helps
1) When you have classes with same name in different namespaces
2) Avoid using really long class name over and over again.
该use关键字用于 PHP 中的别名,它不导入类。这确实有帮助
1) 当您在不同的命名空间中有相同名称的类时
2) 避免一遍又一遍地使用非常长的类名。
回答by Thielicious
Can I use it to import classes?
我可以用它来导入类吗?
You can't do it like that besides the examples above. You can also use the keyword useinside classes to import traits, like this:
除了上面的例子,你不能那样做。您还可以use在 classes 中使用关键字来导入traits,如下所示:
trait Stuff {
private $baz = 'baz';
public function bar() {
return $this->baz;
}
}
class Cls {
use Stuff; // import traits like this
}
$foo = new Cls;
echo $foo->bar(); // spits out 'baz'
回答by Dotun Peter
Namespace is use to define the path to a specific file containing a class e.g.
命名空间用于定义包含类的特定文件的路径,例如
namespace album/className;
class className{
//enter class properties and methods here
}
You can then include this specific class into another php file by using the keyword "use" like this:
然后,您可以使用关键字“use”将这个特定的类包含到另一个 php 文件中,如下所示:
use album/className;
class album extends classname {
//enter class properties and methods
}
NOTE: Do not use the path to the file containing the class to be implements, extends of use to instantiate an object but only use the namespace.
注意:不要使用包含要实现的类的文件的路径,使用扩展来实例化一个对象,而只使用命名空间。
回答by Müseyib ?l?kb?r
Using the keyword "use" is for shortening namespace literals. You can use both with aliasing and without it. Without aliasing you must use last part of full namespace.
使用关键字“use”是为了缩短命名空间文字。您既可以使用别名,也可以不使用别名。如果没有别名,您必须使用完整命名空间的最后一部分。
<?php
use foo\bar\lastPart;
$obj=new lastPart\AnyClass(); //If there's not the line above, a fatal error will be encountered.
?>

