批改状态:合格
老师批语:

<?php// 1.函数作用域$name = '天蓬老师';$email = 'tp@php.cn';function demo1(): string{// 1.globalglobal $name;$res .= 'name = ' .$name . '<br>';// 2.$GLOBALS$res .= 'email = ' .$GLOBALS['email'] . '<br>';return $res;}echo demo1();echo '<hr>';// 2.闭包:使用use()$demo2 = function () use ($name,$email) {return sprintf('name = %s<br>email = %s<br>',$name,$email);};echo $demo2()?>
回调的使用场景:php单线程同步执行,遇到耗时函数时阻塞,可以改为回调函数异步执行

<?php// 回调执行function demo1(string $name): string{return "Hello $name !";}// call_user_func(函数,参数列表)echo call_user_func('demo1','灭绝老师'), '<hr>';echo call_user_func_array('demo1',['php中文网']),'<br>';// 异步调用对象方法class User{// 实例方法public function hello(string $name) : string{return "Hello $name !";}// 静态方法:类调用public static function sum(string $site) :string{return "Hello $site !";}}// 实例方法$res = call_user_func_array([new User,'hello'],['天蓬老师']);echo $res,'<br>';// 静态方法$res = call_user_func_array('User::sum',['PHP中文网']);echo $res;?>
json_encod()
<?php// 数组function demo1():array{return ['status' => 1, 'message' => '成功'];}$res = demo1();print_r($res);echo '<hr>';// 对象function demo2():object{// 匿名类return new class (){public $name = 'admin';public $email = 'admin@qq.com';};}$user = demo2();print_r($user);echo '<hr>';// php内置序列化函数:serializefunction demo3(): string{return serialize(['status' => 1, 'message' => '验证成功']);}$str = demo3();echo $str;echo '<hr>';// 转为json:json_encode()function demo4(): string{return json_encode(['status' => 1, 'message' => '验证成功']);}$str = demo4();echo $str,'<br>';?>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号