laravel-Macroable

  说明:类型为trait,引入后可以在不修改类代码的情况下,为类植入新的方法(类的方法或静态方法均可)。使用__call实现

  引入:

<?php
require 'vendor/autoload.php';
use IlluminateSupportTraitsMacroable;

//$app = require_once 'bootstrap/app.php';

class test {
    use Macroable;
    public $test = 'param test';
    public static $test2 = 'static param test2';
    
}

$o = new test;

  例子:

  (1)植入类方法

$o::macro('run', function () {
    echo $this->test;
});

$o->run();

  (2)植入静态方法

$o::macro('run2', function () {
    echo static::$test2;
});

$o::run2();

  (3)是否植入过该方法

$o::macro('run2', function () {
    echo static::$test2;
});

echo $o::hasMacro('run2');

  (4)merge其他类的public和protected方法

class test2 {
    public function test2Method() {
        return function () {
            echo 'test2 method';
        };
    }
}


$o::mixin(new test2);
$o->test2Method();
原文地址:https://www.cnblogs.com/wangjianheng/p/14071644.html