闭包
将闭包绑定到对象上,来访问类成员
-创建要访问的类
-创建闭包函数
-用Closure类函数bindTo
或bind
进行绑定
-对闭包函数传参,继续类的访问
以下是bindTo()
用法
<?php
namespace chapter4;
use Closure;
//创建一个类
class Index
{
public $name = '笑傲江湖';
public $book = '罗贯中';
public function getInfo()
{
return $this->name . ' : ' . $this->book;
}
}
$index = new Index();
echo $index->getInfo();
echo '<br>';
//创建一个匿名函数
$set = function (string $name,string $book) {
$this->name = $name;
$this->book = $book;
};
//将闭包绑定在对象上,并返回一个新闭包对象,来调用原对象
$closure = $set->bindTo($index);
//var_dump($closure);
$closure('天龙八部', '乔峰');
echo $index->getInfo();
echo '<br>';
//创建静态类
class Index2
{
public static $name = '水浒传';
public static $book = '罗贯中';
public static function getInfo()
{
return static::$name . ' : ' . static::$book;
}
}
$index2 = new Index2();
echo $index2::getInfo();
echo '<br>';
//创建一个匿名函数
$set = function (string $name,string $book) {
static::$name = $name;
static::$book = $book;
};
$closure = $set->bindTo(null,Index2::class);
$closure('红楼梦', '贾宝玉');
echo $index2->getInfo();
以下是bind()
用法
<?php
namespace chapter4;
use Closure;
//使用Closure类里的bind()函数实现闭包对类属性的更新
//创建一个类
class Index3
{
public $name = '笑傲江湖';
public $book = '罗贯中';
public function getInfo()
{
return $this->name . ' : ' . $this->book;
}
}
$index = new Index3;
echo $index->getInfo();
echo '<br>';
//创建一个匿名函数
$set = function (string $name,string $book) {
$this->name = $name;
$this->book = $book;
};
//将闭包绑定在对象上,来调用原对象
//$closure = $set->bindTo($index);
$closure = Closure::bind($set, $index);
//var_dump($closure);
$closure('天龙', '乔峰');
echo $index->getInfo();
echo '<br>';
//创建静态类
class Index4
{
public static $name = '水浒传';
public static $book = '罗贯中';
public static function getInfo()
{
return static::$name . ' : ' . static::$book;
}
}
$index = new Index4();
echo $index->getInfo();
echo '<br>';
//创建一个匿名函数
$set = function (string $name,string $book) {
static::$name = $name;
static::$book = $book;
};
$closure = Closure::bind($set, $index);
$closure('红楼', '贾宝玉');
echo $index::getInfo();
异常
以下是异常处理与自定义异常
<?php
namespace chapter4;
use Exception;
try {
if (true) throw new Exception('验证失败', 101);
}catch (Exception $e){
echo $e->getMessage() . '<br>';
echo $e->getCode() . '<br>';
echo $e->getFile() . '<br>';
echo $e->getLine();
}
echo '<hr>';
//自定义异常处理
class Aexception extends Exception
{
public function __toString()
{
return <<<HEREDOC
<table style="border: red 1px solid" border="1" cellpadding="0" cellspacing="5">
<caption >异常提示内容</caption>
<tr><th>Message</th><th>code</th><th>line</th></tr>
<tr><td>$this->message</td><td>$this->code</td><td>$this->line</td></tr>
</table>
HEREDOC;
}
}
try {
if (true) throw new Aexception('验证登录失败,请重新查证后再次尝试', '888');
}catch (Aexception $e){
echo $e;
}