是否需要包含名称空间文件? [英] Is it required to include the namespace file?

查看:44
本文介绍了是否需要包含名称空间文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我手头上的东西:

This is what I have at hand:

//Person.php
namespace Entity;

class Person{


}

用户文件:

//User.php
use Entity\Person;

$person = new Person;

在这里,如果我不包含Person.php文件,它将失败.如果我将其包括在内,则一切正常.即使使用名称空间,我也绝对需要包含文件吗?如果根本需要包含/需要文件,那么如何有效地使用命名空间?另外,我们可以通过嵌套名称空间来维护文件夹结构吗?

Here, it fails if I don't include the Person.php file. If I include it, the everything works fine. Do I absolutely require to include the file even when using namespaces? If at all we need to include/require files, then how can namespaces be effectively used? Also, can we maintain folder structure by nesting namespaces?

推荐答案

您的问题的答案是是和不是".

The answer to your question is "yes and no".

实际上,必须包含实现类Person的代码,否则该类未定义且无法使用.当不包含代码时,定义应来自何处? php解释器不能猜测类的实现.顺便说一句,在所有编程语言中都是一样的.

Indeed the code implementing class Person has to be included, otherwise the class is not defined and cannot be used. Where should the definition come from, when the code is not included? The php interpreter cannot guess the classes implementation. That is the same in all programming languages, by the way.

但是php中有一个叫做自动加载的东西.它允许自动包括某些文件.该机制基于类名到文件名的映射.因此,最后它归结为php在文件夹结构中搜索以找到一个文件,该文件的名称表明该文件实现了其执行的代码中当前所需的类.

However there is something called Autoloading in php. It allows to automatically include certain files. The mechanism is based on a mapping of class names to file names. So in the end it boils down to php searching through a folder structure to find a file whos name suggests that it implements a class currently required in the code it executes.

但是请不要误会: still 表示必须包含文件.唯一的区别是:包含是自动完成的,因此无需指定显式的includerequire语句.

But don't get this wrong: that still means the file has to be included. The only difference is: the including is done automatically, so without you specifying an explicit include or require statement.

这篇关于是否需要包含名称空间文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆