博客列表 >自动加载及trait案例_1010

自动加载及trait案例_1010

Jet的博客
Jet的博客原创
2019年10月13日 13:22:33787浏览

// 1. 写一个分级的命名空间, 并实现类的自动加载

02.jpg

demo2.php文件

实例

<?php
namespace int;

//自动加载函数
spl_autoload_register(function ($className){
    //str_replace 字符串替换函数 (被替换的字符,DIRECTORY_SEPARATOR,字符串)
    //DIRECTORY_SEPARATOR 系统目录分隔符
    $path = str_replace('\\', DIRECTORY_SEPARATOR, $className);
    $path = __DIR__ . '/' . $path . '.php';
    //file_exists 检查如果$path文件存在,则加载此文件1次
    if(file_exists($path)) include_once $path;
});


echo Test::demo();

运行实例 »

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


test.php文件

实例

<?php
namespace int;

class Test
{
    public static function demo()
    {
        return __METHOD__;
    }
}

运行实例 »

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




// 2. 写一个trait类, 理解它的功能与使用场景

03.jpg


实例

<?php

//子类 > trait > 父类

namespace _1010;

trait Db
{
    public function connect($dsn, $username, $pwd)
    {
        return new \PDO($dsn, $username, $pwd);
    }
}

trait Query
{
    public function get($pdo, $where='')
    {
        $where  = empty($where) ? '' : ' WHERE ' . $where;
        $stmt   = $pdo->prepare('SELECT * FROM `staff` ' . $where . ' LIMIT 1');
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
}

class Client
{
    //在宿主类Client中引入上面声明的两个Trait类/方法集
    use Db;
    use Query;
    public $pdo = null;
    public function __construct($dsn,$username,$pwd)
    {
        $this->pdo = $this->connect($dsn,$username,$pwd);
    }
    public function find($where)
    {
        return $this->get($this->pdo,$where);
    }
}

$dsn        = 'mysql:dbname=staff';
$username   = 'root';
$pwd        = 'root';
$client = new Client($dsn,$username,$pwd);
echo '<pre>' . print_r($client->find('age>30'),true);

运行实例 »

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

 


小结:

1、自动加载,可以实现只需用到才加载,不用不加载,这样使程序运行更好;

2、trait使用级别,子类>trait>父类;trait也是方法集,使用trait好处市可以保存框架源码。





 

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议