美文网首页PHP
(二)从零编写PHP容器-基础数据类型判断

(二)从零编写PHP容器-基础数据类型判断

作者: FinalZero | 来源:发表于2020-02-19 16:14 被阅读0次

项目源码

功能实现

基于example1的Container实现,添加对基本数据类型以及mixed变量的实现支持(赋默认值)

代码实现 Container

public function create($abstract)
{
    // temporary constraint
    static $times = 0;
    if (++$times > 100) {
        $times = 0;
        throw new class('exec too many times in create method.') extends Exception implements ContainerExceptionInterface{ };
    }
    $refClass = new ReflectionClass($abstract);
    if ($refClass->getName() === Closure::class) {
        return function (){};
    } elseif ($refClass->hasMethod('__construct')) {
        $_constructParams = array_map(function (ReflectionParameter $param) {
            if ($param->getClass()) {
                return $this->create($param->getClass()->getName());
            } elseif ($param->isDefaultValueAvailable()) {
                return $param->getDefaultValue();
            } elseif ($param->getType()) {
                return ([
                        'string' => '',
                        'int' => 0,
                        'array' => [],
                        'bool' => false,
                        'float' => 0.0,
                        'iterable' => [],
                        'callable' => function() {}
                    ])[$param->getType()->getName()] ?? null;
            } else {
                return null;
            }
        }, $refClass->getMethod('__construct')->getParameters());
    }
    return $refClass->newInstance(... ($_constructParams ?? []));
}
  • 以下代码主要用于限制方法的最大执行次数,防止相互依赖造成的程序死循环,本例忽略此段代码
    // temporary constraint
    static $times = 0;
    if (++$times > 100) {
        $times = 0;
        throw new class('exec too many times in create method.') extends Exception implements ContainerExceptionInterface{ };
    }

实现思路

  1. 列出无法以类解析或者无法通过new创建的类(仅考虑PHP内部的类)参数列表的数据类型
    • string
    • int
    • array
    • bool
    • float
    • iterable
    • callable
    • Closure

示例

相关文章

网友评论

    本文标题:(二)从零编写PHP容器-基础数据类型判断

    本文链接:https://www.haomeiwen.com/subject/yzvafhtx.html