批改状态:合格
老师批语:匿名类现在用得并不多, 最多是用在对象参数中
//__sleep():当序列化的时候自动调用//__wakeup():当反序列化的时候自动调用class Product{public $name;private $price,$sum;public function __construct($name,$price,$sum){$this->name=$name;$this->price=$price;$this->sum=$sum;}//序列化时自动调用,return array()返回序列化的值public function __sleep(){return array('sum','price');}//反序列化时自动调用public function __wakeup(){$this->total=$this->price*$this->sum;}}$product=new Product('手机',1000,3);$res = serialize($product); //序列化$str = unserialize($res); //反序列化printf('<pre>%s</pre>',print_r($str,true));
图例
自定义异常类
<?phpclass CustomException extends Exception{public function __toString(){return '错误提醒:'.$this->message.'<br>'.'代码异常:'.$this->code;}}class Custom{public $admin;public function __construct($admin){$this->admin = $admin;}}try{$custom = new Custom('12345678qq.com');if(!filter_var($custom->admin,FILTER_VALIDATE_EMAIL)){throw new CustomException('邮箱格式不正确',30);}else{echo '验证成功';}}catch(CustomException $e){echo $e;}

var_dump((new class('user1','123'){public $admin,$password;public function __construct($admin,$password){$this->admin = $admin;$this->password = $password;}}));

了解了如何自定义一个异常, __sleep和__wakeup都用在对象的序列化操作,关于匿名类没有想到什么好的例子,只能写一个最简单的了。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号