批改状态:合格
老师批语:不必与老师的代码相同, 可以有自己的想法
知识点:
一、闭包:
1、在php中闭包即匿名函数,闭包是一个对象,一个clousre类实例;
2、闭包最常用的环境:函数或者方法的回调参数
3、闭包可以将一个执行环境(父级中的变量/状态)封装到匿名函数中
二:闭包中的类方法
1、bindTo():复制当前闭包对象,绑定指定$this和类作用域(实列方法)
2、bind():复制一个闭包对象,绑定指定$this和类作用域(静态方法)
3、__invoke():将闭包对象当成函数用时触发;(魔术方法)
4、__construct(void):构造方法,禁止外部实列化clousre类
5、__toString():将对象当成字符串输出时自动触发;
三:异常类:
Exception {/* 属性 */protected string $message ;protected int $code ;protected string $file ;protected int $line ;/* 方法 */public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )final public getMessage ( void ) : stringfinal public getPrevious ( void ) : Throwablefinal public getCode ( void ) : intfinal public getFile ( void ) : stringfinal public getLine ( void ) : intfinal public getTrace ( void ) : arrayfinal public getTraceAsString ( void ) : stringpublic __toString ( void ) : stringfinal private __clone ( void ) : void}
四、其他
1、array_filter():数组过滤函数,对传入数组中的每一个元素进行处理,返回结果为true元素的组成的新数组;
2、in_array($value,$array);判断$value是否在$array数组中,返回的bool值
3、AEEAY_FILTER_USE_KEY:是数组过滤函数的参数,返回数组中的键值;
4、__callStatic();当访问一个类中不存在静态方法时,会自动触发这个魔术方法
代码:
<?phpnamespace part0;use Closure;$closure=function (string $name) :Closure {return function(string $var) use($name){return sprintf('%s,%s',$name,$var);};};$c=$closure('种业圈');$str=$c('欢迎你');echo $str.'<br>';echo '<hr>';class User{public $name='张无忌';public static $school='明教';private $age=30;public function __toString(){return $this->name.'入'.static::$school.$this->age.'年';}public function set($n){$this->age=$n;}}$user=new User;echo $user;echo '<br>';$set=function(string $name, string $school, int $age): void {$this->name=$name;static::$school=$school;$this->set($age);};$cl=$set->bindTo($user,User::class);$cl('朱老师','php中文网',15);echo $user;
实现效果:
<?phpnamespace one;use Exception;class MyException extends Exception{public function __toString(){return <<< DOC<table border="1" cellspacing="0" cellpadding="5"><tr bgcolor="wheat"><th>错误信息</th><th>代码</th><th>文件</th><th>行号</th></tr><tr><td>$this->message</td><td>$this->code </td><td>$this->file </td><td>$this->line</td></tr></table>DOC;}}try{if(true) throw new MyException('密码不一致',400);}catch(MyException $a){echo $a;};
效果图:
闭包类中:
bind($clousre,$class,Class::class)和$clousre->bindTo($class,Class::class)中的参数,没有类对象(类实列时)直接绑定类时,类实例应为null;
1、bindTo()的使用:
$bind=$colusre->bindTo($class);//闭包绑定类返回新的闭包$bind(...$var);//运行闭包到类,执行绑定到类
2、bind()的使用:
$bind=Clousre::bind($clouser,$class);$bind(...$var);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号