Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:面向对象中的知识 , 我们花了太多的时间, 也希望引起大家足够的重视
//定义一个工作类
class Person {
//初始化赋值
public function __construct(...$args)
{
list($name, $sex, $age) = $args;
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
//当类实例被序列化时
public function __sleep()
{
return ['name', 'sex', 'age'];
}
//当对象字符串被反序列化时
public function __wakeup()
{
$this->name = '小红';
$this->sex = '女';
$this->age = 17;
}
}
//客户端代码
$p1 = new Person('小明', '男', 18);
echo serialize($p1);
$str = serialize($p1);
echo '<br>';
var_dump(unserialize($str));
//定义一个工作类
class Person {
public $name = '小明';
public $sex = '男';
public $age = 18;
}
//客户端代码
$p1 = new Person;
$p2 = $p1;
$p2->name = '小红';
echo $p1->name;
$p3 = clone $p1;
$p3->age = 17;
echo $p1->age;
//自定义一个异常类
class SelfException extends Exception {
public function errMess()
{
$errmsg = '过滤失败:含有非法字符';
return $errmsg;
}
}
//定义一个样本
$email = "小明@php.cn";
//处理异常
try {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//触发/抛出异常
throw new SelfException($email);
}
} catch (SelfException $e) {
//捕获/接受异常
echo $e->errMess();
}
//定义一个接口
interface iPerson {
public function __construct(...$args);
}
//定义一个匿名类
$name = (new class('小明', '男', 18) implements iPerson {
public function __construct(...$args) {
list($name, $sex, $age) = $args;
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
public function getName() {
return $this->name;
}
})->getName();
//客户端代码
echo $name;
//定义一个函数
function getName(object $p1, string $name) {
return $p1->setName($name);
}
//客户端代码
echo getName(new class(){
public function setName($name) {
return $name;
}
},'小明');