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.
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();
?>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
