Blogger Information
Blog 33
fans 0
comment 0
visits 24374
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类与对象进阶知识(匿名类、Trait、自动加载、序列化)20180905 23:00
EmonXu的博客
Original
613 people have browsed it

类与对象的进阶知识,是需要掌握的。

如下代码演示匿名类、Trait、自动加载、序列化。

实例

<?php

//1. 编程: 匿名对象与匿名类的实现过程;

class Player{
    private $name='james';

    public function belongto($team){
        return $this->name.'属于'.$team;
    }
}

echo (new Player())->belongto('湖人'),'<br>';

echo (new class{
    private $name='curry';

    public function belongto($team){
        return $this->name.'属于'.$team;
    }
})->belongto('勇士'),'<hr>';

//2. 编程: Trait类的声明与工作原理;
//原理:PHP不支持多重继承,为了代码复用,引入trait,优先级:自身方法>trait的方法>继承的方法
trait Player1{
    private $name='钓鱼岛';

    public function belongto($team){
        return $this->name.'永远属于'.$team;
    }
}

trait Player2{
    private $name1='苍老师';

    public function belongto($team){
        return $this->name1.'不只属于'.$team;
    }
}

class Player3{
    use Player1,Player2 {
        Player1::belongto insteadof Player2;
        Player2::belongto as belongto1;
    }
}

ECHO (NEW Player3())->belongto('中国'),'<br>';
ECHO (NEW Player3())->belongto1('日 本'),'<hr>';

//3. 编程: 类的自动加载函数的写法;

spl_autoload_register(function ($className){
    require './class/'.$className.'.php';
    //存在命名空间的情况下

//    $className = str_replace("\\","/", $className);
//    require './class/'.$className.'.php';
});

//4. 编程: 对象的序列化与反序列化的原理与应用;

$obj = new player();
/**
 * 对象序列化的特点:
 * 1. 只保存对象中的属性,不保存方法
 * 2. 只保存类名,不保存对象名
 */

echo serialize($obj),'<hr>';
$tmp = serialize($obj);
var_dump(unserialize($tmp));

运行实例 »

点击 "运行实例" 按钮查看在线实例


对于面向对象的理解:

面向对象是相对于面向过程而言的,面向过程是一步步的做,面向对象是将面向过程进一步抽象,提取出类、对象和方法,提高了代码的可复用性,面向对象三要素封装、继承、多态。

Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post