如何在PHP中的构造函数类中添加方法?

时间:2018-03-03 19:44:23

标签: php methods dynamic

我有一个class A,如果其中一个参数设置为true,则需要一个新方法。

A类

Class A{

   private $is_new_method;  

   public function __construct( $is_new_method = false, $new_method_name = "" ){

        $this->is_new_method = $is_new_method;

        if( $this->is_new_method ){
           //TODO : add new method in this class based on $new_method_name 
        }      
   }

}

我看到runkit_method_add但它需要(PECL runkit> = 0.7.0)。

注意:此函数将在如下框架的核心内调用:

$foo = new A();
$foo->myNewFunction();

那么最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

$a = new Inflector([
    'foo' => function($val){echo sprintf('%s calls foo()', $val[0] ?? 'none!').PHP_EOL;},
    'bar' => function($val){echo sprintf('%s calls bar()', $val[0] ?? 'none!').PHP_EOL;},
    'baz' => function($val){echo sprintf('%s calls baz()', $val[0] ?? 'none!').PHP_EOL;},
]);

$a->foo('Ahnold');
$a->bar('Elvis');
$a->baz('Lerhman');
$a->theBreaks('Who');

class Inflector
{
    private $methods = [];

    public function __construct(array $methods)
    {
        $this->methods = $methods;

        //var_dump($this->methods);
    }

    public function __call(string $methodName, $params)
    {
        if (isset($this->methods[$methodName])) {
            $this->methods[$methodName]($params);
        }

        throw new InflectionDeceptionException();
    }

}

class InflectionDeceptionException extends \Exception
{
    public function __construct($message = "Say what?")
    {
        return parent::__construct($message);
    }

}

https://3v4l.org/kLdOp

给出:

Ahnold calls foo()
Elvis calls bar()
Lerhman calls baz()

答案 1 :(得分:0)

谢谢@Jared Farrish! 我根据你的推荐找到了我的解决方案。

Class A{

    private $is_new_method; 

    private $new_method; 

    public function __construct( $is_new_method = false, $new_method_name = "" ){

        $this->is_new_method = $is_new_method;

        if( $this->is_new_method ){
           $new_method = $this->make_my_new_method( $new_method_name ); 
        }      
   }

   private function make_my_new_method( $method_name ){
        $functionName  = "foo_" . $method_name;
        $$functionName = function ( $item ) {
            print_r( $item );
        }
        return $$functionName;
   }

   public function __call( $method, $args){
       if ( isset( $this->new_method ) ) {
           $func = $this->new_method;
           return call_user_func_array( $func, $args );
       }
   }

}