O'Reilly logo

PHP 7 Programming Cookbook by Doug Bierer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using namespaces

An aspect that is critical to advanced PHP development is the use of namespaces. The arbitrarily defined namespace becomes a prefix to the class name, thereby avoiding the problem of accidental class duplication, and allowing you extraordinary freedom of development. Another benefit to the use of a namespace, assuming it matches the directory structure, is that it facilitates autoloading, as discussed in Chapter 1, Building a Foundation.

How to do it...

  1. To define a class within a namespace, simply add the keyword namespace at the top of the code file:
    namespace Application\Entity;

    Note

    Best practice

    As with the recommendation to have only one class per file, likewise you should have only one namespace per file.

  2. The only PHP code that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required