1

是否可以用这样的代码重构匿名函数:

function foo($path, $callback) {
    $callback();
}

$app = array('a', 'b', 'c');

foo('vehicle/:id', function() use ($app) {
    echo $app[0];
});

我试过这个,但它没有回应任何东西:

function foo($path, $callback) {
    $callback();
}

$vehicleCallback = function() use ($app) {
    echo $app[0];
};

$app = array('a', 'b', 'c');

foo('vehicle/:id', $vehicleCallback);

其他变体给了我语法错误。如果这很重要,我希望将这些函数移动到一个单独的文件中。

这是我的最终目标

回调.php

$cb1 = function () use ($app) {
    // things
};

$cb2 = function () use ($app) {
    // things
};

// ...more callbacks

路由器.php

require 'callbacks.php';

$app = new \Foo();

// code that might possibly manipulate $app

$app->bar('/some/relative/path/:param1', $cb1);
$app->bar('/another/relative/path', $cb2);

// possibly more code that mutates $app and then more callbacks
4

1 回答 1

0

您绝对应该打开 error_reporting:

注意:未定义的变量:app in ... 第 6 行

当你移动线路时:

$app = array('a', 'b', 'c');

在脚本的开头你会得到结果a

编辑

你可以$app这样使用:

<?php

function foo($path, $callback, $app) {
    $callback($app);
};

$vehicleCallback = function($app) {
    echo $app[0];
};

$app = array('a', 'b', 'c');

foo('vehicle/:id', $vehicleCallback, $app);

编辑2

您的班级的示例代码

<?php

$cb1 = function ($app, $path) {
    // things
    $app->display('cb1 '.$path.'<br />');
};

$cb2 = function ($app, $path) {
    // things
    $app->display('cb2 '.$path);
};


class Foo {
    public function display ($string) {
        echo strtoupper($string);
    }

    public function bar ($path, $closure) {
        $closure($this, $path);
    }
}


$app = new \Foo();

// code that might possibly manipulate $app

$app->bar('/some/relative/path/:param1', $cb1);
$app->bar('/another/relative/path', $cb2);

// possibly more code that mutates $app and then more callbacks
于 2014-07-22T08:48:11.500 回答