| Start |
|---|
| Declaring namespaces A namespace declaration can look as follows:
It is recommended to only declare a single namespace per file, even though you can declare as many as you like in a single file: Every time you declare a namespace, classes you define after that will belong to that namespace: A namespace declaration can be used multiple times in different files. The example above defined three classes in the |
| Referencing a class or function in a namespace As shown in Declaring Namespaces (opens new window), we can define a class in a namespace as follows: To reference this class the full path (including the namespace) needs to be used: This can be shortened by importing the class via the As for PHP 7.0 you can group various Sometimes two classes have the same name. This is not a problem if they are in a different namespace, but it could become a problem when attempting to import them with the This can be solved by defining a name for the alias yourself using the To reference a class outside the current namespace, it has to be escaped with a |
| Declaring sub-namespaces To declare a single namespace with hierarchy use following example: The above example creates: constant class function |
| What are Namespaces? The PHP community has a lot of developers creating lots of code. This means that one library’s PHP code may use the same class name as another library. When both libraries are used in the same namespace, they collide and cause trouble. Namespaces solve this problem. As described in the PHP reference manual, namespaces may be compared to operating system directories that namespace files; two files with the same name may co-exist in separate directories. Likewise, two PHP classes with the same name may co-exist in separate PHP namespaces. It is important for you to namespace your code so that it may be used by other developers without fear of colliding with other libraries. RemarksFrom the PHP documentation (opens new window): What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world. Note that top-level namespaces |
Read Article
https://develop.horje.com/learn/1434/reference