PHP Type Hinting not working

I am trying to use the Type Hinting function in my application, but something is not working correctly. I tried the following

define('PULSE_START', microtime(true)); require('../Pulse/Bootstrap/Bootstrap.php'); $app = new Application(); $app->run(); $app->get('/404', function(Application $app) { $app->error(404); }); 

And instead of 404 output, I got this

 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 

I don’t understand, the Application class is a class with names (Pulse \ Core \ Application), but I created an alias, so I don’t think the problem is.

+4
source share
2 answers

From the fact that none is given as a passed type value, I think get does not pass a parameter when using closure. To get the $ app to close, you can use use the application.

 $app->get('/404', function() use ($app) { $app->error(404); }); 

And make sure your get method passes $this as the first argument to an anonymous function.

+1
source

Typehinting does not work this way - it requires that the parameter be of the specified type, but you need to create code that will configure the parameters passed to close. A very simple implementation of such smart arguments:

 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); }); 
+1
source

Source: https://habr.com/ru/post/1492753/


All Articles