简体   繁体   English

正确使用php名称空间

[英]Using php namespaces properly

I am trying to figure out how to use the namespace in php. 我试图弄清楚如何在php中使用名称空间。 I have been reading about how to use it and for some reason I can not get it to work. 我一直在阅读有关如何使用它的信息,由于某种原因,我无法使其正常工作。 I have two files one which I have stored in Applications/Database/Classes file name is DatabaseConnection.php and the other in the root directory called DB.php inside the DatabaseConnection.php file I have the following code: 我有两个文件,其中一个存储在Applications/Database/Classes文件名是DatabaseConnection.php ,另一个DB.phpDatabaseConnection.php文件内名为DB.php的根目录中,我有以下代码:

<?php
    function hello()
    {
        echo "hello";
    }
?>

This is the DB.php file contents: 这是DB.php文件的内容:

<?php
namespace Applications\Database\Classes;
ini_set('display_errors', true);
hello();
?>

Maybe I am completely missing how to use it properly but if I set a namespace is that the same as using include or require ? 也许我完全不知道如何正确使用它,但是如果我设置一个名称空间与使用includerequire相同吗? I might be completely misunderstanding how to use it. 我可能完全误会了如何使用它。 I am new to OOP and have never heard of namespaces until I started trying to learn OOP? 我是OOP的新手,在开始学习OOP之前从未听说过名称空间? Can someone point out what I did wrong. 有人可以指出我做错了什么。

Namespaces are for organizing your code in so that you can divide components up and help with the readability. 命名空间用于组织代码,以便您可以划分组件并提高可读性。 For example if I have a class Pittbull and another Dashund I can place them into a namespace like so for organization: 例如,如果我有一个Pittbull类和另一个Dashund类, Dashund可以将它们放入组织的命名空间中,例如:

Animals.Dogs.Pittbull
Animals.Dogs.Dashund

This also helps with potential collisions like the below: 这也有助于避免潜在的碰撞,如下所示:

Animals.Dogs.Misc
Animals.Cats.Misc

The Misc class exists twice in this instance, but instead of there being a conflict of which Misc to use, you can use the same class name for both classes (and have different properties and methods inside of them) and not have a conflict of which one you want to use. 在这种情况下, Misc类存在两次,但是可以使用相同的类名(并且在它们内部具有不同的属性和方法),而不必使用哪个Misc冲突。您要使用的一种。

The require keyword is a completely different concept and is used to load actual files into the executing script. require关键字是一个完全不同的概念,用于将实际文件加载到执行脚本中。

Instruction how to use autoloading in PHP (PSR-0): 有关如何在PHP(PSR-0)中使用自动加载的说明:
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

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

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