
批改狀態(tài):合格
老師批語:不必與老師的代碼相同, 可以有自己的想法
知識點:
一、閉包:
1、在php中閉包即匿名函數(shù),閉包是一個對象,一個clousre類實例;
2、閉包最常用的環(huán)境:函數(shù)或者方法的回調參數(shù)
3、閉包可以將一個執(zhí)行環(huán)境(父級中的變量/狀態(tài))封裝到匿名函數(shù)中
二:閉包中的類方法
1、bindTo():復制當前閉包對象,綁定指定$this和類作用域(實列方法)
2、bind():復制一個閉包對象,綁定指定$this和類作用域(靜態(tài)方法)
3、__invoke()
:將閉包對象當成函數(shù)用時觸發(fā);(魔術方法)
4、__construct(void)
:構造方法,禁止外部實列化clousre類
5、__toString()
:將對象當成字符串輸出時自動觸發(fā);
三:異常類:
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 ) : string
final public getPrevious ( void ) : Throwable
final public getCode ( void ) : int
final public getFile ( void ) : string
final public getLine ( void ) : int
final public getTrace ( void ) : array
final public getTraceAsString ( void ) : string
public __toString ( void ) : string
final private __clone ( void ) : void
}
四、其他
1、array_filter():數(shù)組過濾函數(shù),對傳入數(shù)組中的每一個元素進行處理,返回結果為true元素的組成的新數(shù)組;
2、in_array($value,$array);判斷$value是否在$array數(shù)組中,返回的bool值
3、AEEAY_FILTER_USE_KEY:是數(shù)組過濾函數(shù)的參數(shù),返回數(shù)組中的鍵值;
4、__callStatic()
;當訪問一個類中不存在靜態(tài)方法時,會自動觸發(fā)這個魔術方法
代碼:
<?php
namespace part0;
use Closure;
$closure=function (string $name) :Closure {
return function(string $var) use($name){
return sprintf('%s,%s',$name,$var);
};
};
$c=$closure('種業(yè)圈');
$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中文網(wǎng)',15);
echo $user;
實現(xiàn)效果:
<?php
namespace 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)中的參數(shù),沒有類對象(類實列時)直接綁定類時,類實例應為null;
1、bindTo()的使用:
$bind=$colusre->bindTo($class);//閉包綁定類返回新的閉包
$bind(...$var);//運行閉包到類,執(zhí)行綁定到類
2、bind()的使用:
$bind=Clousre::bind($clouser,$class);$bind(...$var);
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號