是否可以从这样的代码中重构匿名函数:
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);
其他变体给了我语法错误。我希望将这些函数移动到一个单独的文件中,如果这很重要的话。
$cb1 = function () use ($app) {
// things
};
$cb2 = function () use ($app) {
// things
};
// ...more callbacks
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
答案 0 :(得分:0)
你一定要开启error_reporting:
注意:未定义的变量:第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);
<强> EDIT2 强>
您班级的示例代码
<?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