简体   繁体   English

PHP-通过引用传递/存储对象实例方法?

[英]PHP - Passing/storing object instance methods by reference?

As part of an attempt to get better at OOP, I'd like to implement a task queueing object that can build a list of tasks and execute them. 为了提高OOP的能力,我想实现一个任务队列对象,该对象可以构建任务列表并执行它们。 And I am writing in PHP, because most of the work that I do has to be in that language, and this is in the context of a very basic web framework I'm trying to build. 我正在用PHP编写代码,因为我所做的大部分工作都必须使用该语言,并且这是在我要构建的非常基本的Web框架的背景下进行的。

At its simplest, the tasks would consist of a function, an array of variables, a boolean to express that the task has been completed. 最简单的说,任务将由一个函数,一个变量数组和一个布尔值组成,以表示任务已完成。

Is there a way to pass an object's function in a way that I can store it in a list and then execute it later? 有没有一种方法可以传递对象的功能,使我可以将其存储在列表中,然后在以后执行它? Ideally I'd like something like: 理想情况下,我想要类似的东西:

$tasks->register($log->outputAllEntries, $logLevel);
$tasks->register($database->remove, $someRecord);
$tasks->register($log->toHTML, null);

and then later 然后再

$tasks->run();

And the run method in tasks would then run: 然后任务中的运行方法将运行:

$log->outputAllEntries($logLevel);
$database->remove($someRecord);
$log->toHTML();

I'm having trouble figuring out how to store the reference to the functions that I want to run... is there some way of doing that in PHP? 我在弄清楚如何存储对我要运行的函数的引用时遇到了麻烦...在PHP中有某种方法可以做到这一点吗? Or am I thinking about the problem ins a stupid kind of way? 还是我以一种愚蠢的方式思考问题? This seems like something pretty easy to do in Javascript, but I'm not having any luck in PHP. 用Javascript似乎很容易做到这一点,但是我在PHP中没有任何运气。

There are a few ways you could implement this. 有几种方法可以实现此目的。 A simple approach would, instead of: 一个简单的方法将代替:

$tasks->register($log->outputAllEntries, $logLevel);

you would do 你会做

$tasks->register($log, 'outputAllEntries', array($logLevel));

You would have for your functions: 您将拥有自己的功能:

function register($class, $method, $params) {
    $this->tasks[] = array($class, $method, $params);
}

function run() {
    foreach($this->tasks as $task) {
        list($class, $method, $params) = $task;
        call_user_func_array(array($class, $method), array($params));
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM