Backend Development 2 min read
Using Namespaces, Aliases, Traits, and Closures in PHP
This article demonstrates how to use PHP namespaces with the `use` keyword, create aliases for classes, functions, and constants, incorporate traits, and capture variables in anonymous functions, providing clear code examples for each concept.
php中文网 Courses
php中文网 Courses
This article provides practical examples of several advanced PHP features, including namespace declarations, aliasing with the use keyword, trait inclusion, and variable capture in anonymous functions.
1. Namespace usage
<?php
namespace admin\controller;
use \core\controller; //引入命名空间
class ArticleController extends Controller{
public function index(){
}
}
?>2. Alias keyword
<?php
namespace space;
function display(){}
class Man{}
const PI = 3.14;
namespace space1;
class Man{};
//use space\Man; //错误:当前空间已经存在Man
use space\Man as M;
use function space\display as dis;
use const space\PI as D;
?>3. Trait inclusion
<?php
trait A{
function testTrait(){
echo 'This is Trait A!';
}
}
class B {
use A;
}
$b = new B();
$b->testTrait();
?>4. Anonymous function with variable capture
<?php
function F1(){
$ok = "HelloWorld";
$a = function() use ($ok) {
echo "$ok";
};
$a();
}
F1();
?>Written by
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
0 followers
Reader feedback
How this landed with the community
Rate this article
Was this worth your time?
Discussion
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.