笔记:自动加载与使用Closure实现private调用

自动加载

<?php

// 方法1 使用__autoload魔术方法 不推荐使用
function __autoload($className){
    echo "----__autoload----".$className.PHP_EOL;
    require_once($className.".php");
}

// 方法2 使用spl_autoload_register,

//传入方法名
function autoLoad($className){
    require_once($className.".php");
}
spl_autoload_register("autoLoad");

//闭包写法
spl_autoload_register(function($className){
    require_once($className.".php");
});

$A = new TestClassA();
$A->printf();

使用Closure实现private调用

<?php
class T{
    public static $maps = array(1,2,3,4);
    
    private function show()
    {
        echo "我是T里面的私有函数:show\n";
    }

    protected  function who()
    {
        echo "我是T里面的保护函数:who\n";
    }

    public function name()
    {
        echo "我是T里面的公共函数:name\n";
    }
}

class Loader{

    private $loadMaps = array();

    function __construct(){
        echo "我是Loader::__construct\n";
    }

    public function getLoadMaps(){
        return $this->loadMaps;
    }
}

// Test1 演示 通过Closure 为private赋值
$loader = new Loader();
Closure::bind(function() use($loader){
    $loader->loadMaps = T::$maps;
}, null, Loader::class)();

var_dump($loader->getLoadMaps());

// Test2 演示 通过Closure 调用private方法
Closure::bind(function() use($loader){
    $this->show();
    $this->who();
    $this->name();
}, new T(), t::class)();

点赞

发表评论

邮箱地址不会被公开。 必填项已用*标注