PHP OOPLesson 55Free preview
PHP Namespaces
This lesson is part of PHP · All levels
Summary
Namespace groups class names, functions, and constants into named containers so that no clashes between libraries occur. The namespace declaration is placed at the top of the file using the namespace keyword, and the class usage of the other namespace is imported with the use. From within the namespace, you can access global members with a slash backwards in front.
Key points
- Namespace is first declared in a file using the namespace Name\Sub;.
- Use is used to import classes from other namespaces to make the writing shorter.
- The \ before sign refers to the global namespace, e.g. new \DateTime().
- Namespace avoids name clashes when two libraries have a class of the same name.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.