批改状态:未批改
老师批语:
深入类的理解与对象序列化
主要知识点
1)匿名对象与匿名类的实现
2)Trait类的声明与工作
3)类的自动加载函数
4)对象的序列化与反序列化
面向对象编程的基本理解
* 个人认为在解决问题的过程中,进一步分析出每个参与解决问题的对象
* 并确定这些对象的行为,最终由这些对象解决问题的编程思想,设计出这些的图纸我们叫做类
* 这就是我们常说的类是对象的抽象化,对象是类的具体化
* 简单介绍面向对象编程(OOP)的基本特性
* 四大特征:
* 抽象,封装,继承,多态
代码
匿名对象与匿名类的实现过程
<?php
class Person
{
private $name;
public function __construct($name) {
$this->name = $name;
}
public function show(){
return 'my name is'.$this->name;
}
}
// 匿名对象
echo (new Person('jack'))->show().'<hr>';
// 匿名函数
echo (new class ('波斯猫') {
private $type;
public function __construct($type)
{
$this->type = $type;
}
public function whatIt()
{
return '这是'.$this->type.'品--种';
}
})->whatIt().'<br>';Trait类的声明与工作原理
<?php
class Animal
{
protected $name;
public function __construct($name='tom') {
$this->name = $name;
}
public function doSomething($name='狂奔'){
return $this->name.'在'.$name;
}
}
trait Sport
{
public $nickName1 = 'jack';
public function doSomething($name='跳')
{
return $this->name.'和'.$this->nickName1.'在'.$name;
}
}
trait Feed
{
public $nickName2 = 'malk';
public function doSomething($name='苹果')
{
return $this->name.'在吃'.$name;
}
}
class Dog extends Animal
{
use Sport, Feed {
Sport::doSomething insteadof Feed;
Feed::doSomething as DoIt;
}
}
$dog = new Dog();
echo $dog->doSomething().'<hr>';
echo $dog->DoIt();类的自动加载函数的写法
demo4.php
<?php
// 类的自动加载
spl_autoload_register(function ($className){
require './class/'.$className.'.php';
});
echo Test1::CLASS_NAME, '<hr>';
echo Test2::CLASS_NAME, '<hr>';class/test1.php
<?php
class Test1
{
const CLASS_NAME = __CLASS__;
}class/test2.php
<?php
class Test2
{
const CLASS_NAME = __CLASS__;
}对象的序列化与反序列化的原理与应用
<?php
// 对象的序列化与反序列化的原理与应用
/**
* 对象序列化的特点:
* 1. 只保存对象中的属性,不保存方法
* 2. 只保存类名,不保存对象名
*/
class Animal
{
private $nickName;
private $type;
private $both;
function __construct($nickName = "", $type = "", $both = "") {
$this->nickName = $nickName;
$this->type = $type;
$this->both = $both;
}
function say() {
echo "来自" . $this->both . " 的" . $this->type . " 昵称叫" . $this->nickName . "<br>";
}
}
$cat = new Animal("喵喵怪", "波斯猫", "埃及");
$cat_string = serialize($cat); //把一个对象串行化,返一个字符串
echo $cat_string . "<br>"; //串行化的字符串我们通常不去解析
$cat2 = unserialize($cat_string); //把一个串行化的字符串反串行化形成对象$cat2
echo '<hr>';
var_dump($cat2);
echo '<hr>';
$cat2->say();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号