Discover PHP7’s Powerful New Features: Namespaces, Traits, Generators, and More

PHP7 brings a host of performance improvements and new language features—including refined namespace usage, interfaces, traits, generators, closures, Zend OPcache, and a built‑in HTTP server—each illustrated with practical code examples and best‑practice recommendations for modern backend development.

21CTO
21CTO
21CTO
Discover PHP7’s Powerful New Features: Namespaces, Traits, Generators, and More

1. Namespaces

Namespaces are widely used in PHP7; the article highlights several practical tips and pitfalls.

Multiple imports : avoid combining several classes in a single use statement; write one use per line.

<?php
use Symfony\HttpFoundation\Request;
use Symfony\HttpFoundation\Rese;
use Symfony\HttpFoundation\Cookie;
?>

Multiple namespaces in one file : possible but violates the "one class per file" best practice.

<?php
namespace Foo {
    // code
}
namespace Bar {
    // code
}
?>

Global namespace : to use PHP's native Exception class, prefix it with a backslash.

<?php
namespace My\App;
class Foo {
    public function doSomething() {
        $exception = new \Exception();
    }
}
?>

2. Interfaces

Using interfaces makes code more flexible and decoupled; callers depend only on the contract, not on concrete implementations.

3. Traits

Traits, introduced in PHP 5.4, are reusable pieces of functionality that can be mixed into multiple classes, similar to Ruby mixins.

Why use traits : example with Car and Phone both needing GPS functionality without forcing an unnatural inheritance hierarchy.

Creating a trait :

<?php
trait MyTrait {
    // implementation
}
?>

Using a trait :

<?php
class MyClass {
    use MyTrait;
    // class implementation
}
?>

4. Generators

Generators, added in PHP 5.5, provide simple iterators without implementing the Iterator interface. They yield values lazily, calculating each element only when needed.

Simple generator example :

<?php
function makeRange($length) {
    for ($i = 0; $i < $length; $i++) {
        yield $i;
    }
}
foreach (makeRange(1000000) as $i) {
    echo $i, PHP_EOL;
}
?>

Real‑world scenario: processing a large CSV file with a generator to keep memory usage low.

<?php
function getRows($file) {
    $handle = fopen($file, 'rb');
    if ($handle === false) {
        throw new Exception();
    }
    while (!feof($handle)) {
        yield fgetcsv($handle);
    }
}
foreach (getRows('data.csv') as $row) {
    print_r($row);
}
?>

5. Closures

Closures (anonymous functions) are treated as first‑class objects in PHP; they implement the __invoke() magic method.

<?php
$closure = function ($name) {
    return sprintf('Hello %s', $name);
};
echo $closure('Beck'); // outputs "Hello Beck"
?>

Using use to import variables into a closure:

<?php
function enclosePerson($name) {
    return function ($doCom) use ($name) {
        return sprintf('%s, %s', $name, $doCom);
    };
}
$clay = enclosePerson('Clay');
echo $clay('get tea!'); // outputs "Clay, get tea!"
?>

6. Zend OPcache

Bytecode caching is not new to PHP, but since PHP 5.5 the built‑in Zend OPcache stores compiled opcodes, eliminating the need to parse and compile scripts on every request and dramatically improving performance.

7. Built‑in HTTP Server

PHP includes a built‑in web server since PHP 5.4, useful for local development but not recommended for production.

Starting the server : php -S localhost:4000 Configuring the server : php -S localhost:8000 -c app/config/php.ini Router script : the built‑in server lacks .htaccess support, so a router script can direct requests. To detect if the script runs under the built‑in server:

<?php
if (php_sapi_name() === 'cli-server') {
    // built‑in web server logic
}
?>

Source: PHP public account.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend Developmentphp7closuresGeneratorsOPcacheNamespacesTraits
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.