Php 如何准备方法/函数调用,以便在以后调用它?

Php 如何准备方法/函数调用,以便在以后调用它?,php,oop,Php,Oop,在以后实际执行时,“准备/存储函数调用”*的最佳方式是什么 (*参数数量待定) 我现在所拥有的: function addCall($className, [$parameter [, $parameter ...]]) { $this->calls[] = func_get_args(); } 那我就做: foreach($this->calls as $args) { $r = new ReflectionClass(array_shift($args)

在以后实际执行时,“准备/存储函数调用”*的最佳方式是什么

(*参数数量待定)

我现在所拥有的:

function addCall($className, [$parameter [, $parameter ...]]) 
{ 
    $this->calls[] = func_get_args();
}
那我就做:

foreach($this->calls as $args) 
{ 
    $r = new ReflectionClass(array_shift($args));
    $instances[] = $r->newInstanceArgs($args);
}
这在我看来不是很糟糕,包括“参数数量待定”特性

如何改进代码


提前感谢您

您可能对 如何实现它取决于您或您使用的框架。
但这些模式通常会叠加起来。因此,也要仔细阅读“周围”模式,以便能够就实际实现做出正确的选择(或选择现有库)

完全非正式的:

<?php
function foo($a, $b) {
    return 'foo#'.($a+$b);
}

function bar($a,$b,$c) {
    return 'bar#'.($a-$b+$c);
}

$cmds = array();
$cmds[] = function() { return foo(1,2); };
$cmds[] = function() { return bar(1,2,3); };
$cmds[] = function() { return bar(5,6,7); };
$cmds[] = function() { return foo(9,7); };
$s = new stdClass; $s->x = 8; $s->y = 8;
$cmds[] = function() use($s) { return foo($s->x,$s->y); };


// somewhere else....
foreach($cmds as $c) {
    echo $c(), "\n";
}

我个人只想使用
调用用户函数数组
,但从面向对象的角度看,这看起来更糟。但是,它应该适用于您正在尝试做的事情。我想知道以“纯”oop方式编写此概念的最佳方式是什么。。。在不使用反射或调用_user _func*+1的情况下,进行良好的解释并推荐有价值的设计模式。还可以查看ircmaxell的“与Anthony一起编程”视频:
<?php
interface ICommand {
    public function /* bool */ Execute();
}

class Foo implements ICommand {
    public function __construct($id) {
        $this->id = $id;
    }
    public function Execute() {
        echo "I'm Foo ({$this->id})\n";
        return true;
    }
}

class Bar implements ICommand {
    public function __construct($id) {
        $this->id = $id;
    }
    public function Execute() {
        echo "I'm Bar ({$this->id})\n";
        return true;
    }
}

$queueCommands = new SplPriorityQueue();

$queueCommands->insert(new Foo('lowPrio'), 1);
$queueCommands->insert(new Foo('midPrio'), 2);
$queueCommands->insert(new Foo('highPrio'), 3);
$queueCommands->insert(new Bar('lowPrio'), 1);
$queueCommands->insert(new Bar('midPrio'), 2);
$queueCommands->insert(new Bar('highPrio'), 3);

// somewhere else....
foreach( $queueCommands as $cmd ) {
    if ( !$cmd->execute() ) {
        // ...
    }
}