1、sleep(), wakeuup()实例
代码示例
<?php
abstract class User{
protected $name = '李明';
private $age = 30;
}
class Infor extends User{
public $sex = '男';
private $isStudent = false;
protected static $nationality = '中国/CHINA';
public function __get($name)
{
return $this->$name;
}
public function __sleep(): array
{
return ['name', 'sex', 'isStudent'];
}
public function __wakeup()
{
$this->age = 35;
$this->sex = '保密';
}
}
$infor = new Infor();
echo "序列化--" . serialize($infor);
echo "<hr>";
$in = serialize($infor);
echo "反序列化--" ;
var_dump(unserialize($in));
?>
2、自定义异常类, 处理用户登录与验证
- __toString() 方法用于一个类被当成字符串时应怎样回应
代码示例
<?php
class MyException extends Exception
{
public function __construct($message,$code){
$this->code = $code;
$this->message = $message;
}
//重写异常信息输出格式
public function __toString()
{
return '登录失败!['.$this->code.']:'.$this->message;
}
}
try{
$username = $_POSt['username'];
$password = $_POST['password'];
if($username !='zcx123'){
throw new MyException('用户名不存在',1);
}elseif($password !='zcx123456'){
throw new MyException('密码错误',2);
}
}catch(MyException $e){
echo $e;
}
?>
3、匿名函数
代码示例
<?php
interface iDb
{
public function __construct(...$params);
}
$res = (new class ('mysql:host=localhost;dbname=forum', 'root', 'root') implements iDb {
private $db = null;
public function __construct(...$params)
{
$this->db = new PDO($params[0],$params[1],$params[2]);
}
public function select($where="")
{
$where = empty($where) ? '' : ' WHERE ' . $where;
return $this->db
->query('SELECT uId,uName FROM tb1_user ' . $where . ' LIMIT 4')
->fetchAll(PDO::FETCH_ASSOC);
}
}
)->select();
printf('<pre>%s</pre>', print_r($res, true));
学习总结
本节课我们学习了sleep()、wakeup()、异常类和匿名函数。通过反复看视频和参考其他同学的作业对异常类知识基本了解,还需要后期的实战来强化。