[英]PHP Type Hinting is not working
我正在嘗試在我的應用中使用“類型提示”功能,但某些功能無法正常使用。 我嘗試了以下
define('PULSE_START', microtime(true));
require('../Pulse/Bootstrap/Bootstrap.php');
$app = new Application();
$app->run();
$app->get('/404', function(Application $app)
{
$app->error(404);
});
而我得到的不是404輸出
Catchable fatal error: Argument 1 passed to {closure}() must be an instance of Pulse\Core\Application, none given in E:\Server\xampp\htdocs\web\pulse\WWW\Index.php on line 23
我不明白,Application類是一個命名空間類(Pulse \\ Core \\ Application),但是我創建了一個Alias,所以我不認為這就是問題。
由於none
給出none
作為傳遞的類型值的事實,我認為使用閉包時不會傳遞參數。 要將$ app放入閉包中,可以use
該應用程序。
$app->get('/404', function() use ($app)
{
$app->error(404);
});
並確認您的get
方法將$this
作為匿名函數的第一個參數傳遞。
Typehinting不能那樣工作-它要求參數為給定類型,但是您必須創建代碼來自行調整傳遞給閉包的參數。 此類聰明論點的非常簡單的實現:
class Application{
private $args = array(); //possible arguments for closure
public function __construct(){
$this->args[] = $this; //Application
$this->args[] = new Request;
$this->args[] = new Session;
$this->args[] = new DataBase;
}
public function get($function){
$rf = new ReflectionFunction($function);
$invokeArgs = array();
foreach($rf->getParameters() as $param){
$class = $param->getClass()->getName();
foreach($this->args as $arg) {
if(get_class($arg) == $class) {
$invokeArgs[] = $arg;
break;
}
}
}
return $rf->invokeArgs($invokeArgs);
}
}
$app = new Application();
$app->get(function (Application $app){
var_dump($app);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.