Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
<?php
// 1.函数作用域
$name = '天蓬老师';
$email = 'tp@php.cn';
function demo1(): string
{
// 1.global
global $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内置序列化函数:serialize
function 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>';
?>