Book Image

PHP 7 Programming Cookbook

By : Doug Bierer
Book Image

PHP 7 Programming Cookbook

By: Doug Bierer

Overview of this book

PHP 7 comes with a myriad of new features and great tools to optimize your code and make your code perform faster than in previous versions. Most importantly, it allows you to maintain high traffic on your websites with low-cost hardware and servers through a multithreading web server. This book demonstrates intermediate to advanced PHP techniques with a focus on PHP 7. Each recipe is designed to solve practical, real-world problems faced by PHP developers like yourself every day. We also cover new ways of writing PHP code made possible only in version 7. In addition, we discuss backward-compatibility breaks and give you plenty of guidance on when and where PHP 5 code needs to be changed to produce the correct results when running under PHP 7. This book also incorporates the latest PHP 7.x features. By the end of the book, you will be equipped with the tools and skills required to deliver efficient applications for your websites and enterprises.
Table of Contents (22 chapters)
PHP 7 Programming Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 should precede the keyword namespace would be a comment and/or the keyword declare:

    <?php
    declare(strict_types=1);
    namespace Application\Entity;
    /**
     * Address
     *
     */
    class Address
    {
      // some code
    }
  3. In PHP 5, if you needed to access a class in an...