Question

I am trying to use Type Hinting feature in my app 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 dont understand it, the Application class is a namespaced class (Pulse\Core\Application) but I have created an Alias, so I dont think thats the issue.

Was it helpful?

Solution

From the fact that none is being given as the passed in type value I'm thinking get isn't passing a parameter when using the closure. To get $app into the closure you can use the application instead.

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

And verify that your get method is passing $this as the first argument of the anonymous function.

OTHER TIPS

Typehinting does not work that way - it requires parameter to be of given type, but you have to create code that will adjust parameters passed to the closure for yourself. 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);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top