Modern PHP(一)特性

命名空间

作用:类似于目录结构规范类,有效避免类冲突,是实现自动加载的前提。

//定义命名空间
namespace Symfony\Component\HttpFoundation;

//使用命名空间和默认的别名
use Symfony\Component\HttpFoundation\Response;

//导入函数和常量
use func Namespace\functionName;
use const Namespace\CONST_NAME;
全局命名空间示例
    namespace My\app;
    class Foo
    {
        public function doSomethind()
        {
            //$exception = new Exception(); //会报错,My\app\Exception 类不存在
            //应该在全局中引入Exception类
            $exception = new \Exception();
        }
    }

详细可查看博客:PHP 面向对象 (三)命名空间

面向接口编程

//你定义的接口
interface Documentable
{
    public function getId();
    public function getContent();
}

//你定义的类
class DocumentStore
{
    protected $data = [];

    //方法参数为 实现Documentable接口 的 类的实例对象
    public function addDocument(Documentable $document)
    {
        $key = $document->getId();
        $value = $document->getContent();
        $this->data[$key] = $value;
    }

    public function getDocuments()
    {
        return $this->data;
    }
}

//别人想用你写的DocumentStore类, 他只需要实现了Documentable接口,而不需要知道DocumentStore类的具体细节,即可使用。这就是面向接口编程
class CommandOutputDocument implements Documentable
{
    protected $command;

    public function __construct($command)
    {
        $this->command = $command;
    }

    public function getId()
    {
        return $this->command;
    }

    public function getContent()
    {
        return shell_exec($this->command);
    }
}

//使用
$command = new CommandOutputDocument('cat /etc/hosts');
$document = new DocumentStore();
$document->addDocument($command);
$document->getDocuments();

详细可查看博客:PHP 面向对象 (九)面向对象三大特征

性状

性状 traits

性状是类的部分实现,常量,属性和方法(像是接口)

提供模块化的实现(像是类)

主要用于解耦,减少无效代码的重复

详细可查看博客:PHP 面向对象 (十)Traits

生成器

//一个简单的生成器,就是函数,加上断点
function myGenerator()
{
    yield 'value1';
    yield 'value2';
    yield 'value3';
}

foreach(myGenerator() as $yieldValue){
    echo $yieldedValue.PHP_EOL;
}

即输出
value1
value2
value3
使用生成器处理大csv文件
//程序只会占用一行csv字符的内存
function getRows($file){
    $handle = fopen($file, 'rb');
    if($handle === false){
        throw new Exception();
    }
    while (feof($handle) === false){
        yield fgetcsv($handle);
    }
    fclose($handle);
}

foreach (getRows('data.csv') as $orw){
    print_r($row);//处理单行数据
}

提示:简单的excel相关需求,可改用csv格式,csv格式操作更加简洁,速度会更快。

闭包

原理:闭包对象实现了__invoke()魔术方法,只要变量名后面有(), php就会查找并调用该魔术方法

//创建简单的闭包
$closure = function ($name){
    return sprintf('Hello %s', $name);
};

echo $closure("josh");
附加状态,使用外部变量
function enclosePerson($name){
    return function ($doComand) use ($name){
        return sprintf('%s, %s', $name, $doComand);
    };
}

$clay = enclosePerson('Clay');
echo $clay('get me sweet tea!');

Zend OPcache

字节码缓存的作用:基于每次请求php文件,php解析器会在执行php脚本时,先解析php脚本代码,把php代码编译成一系列Zend操作码,然后执行字节码。每次都可以执行的话,会消耗很多资源。所以字节码的缓存在于,缓存预先编译好的字节码,减少应用响应时间,降低系统资源的压力。

本作品采用《CC 协议》,转载必须注明作者和本文链接
写的不好,就当是整理下思绪吧。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!