php - How can I force expression given as function parameter to be calculated after the function call? -


i writing own testing class. problem have encountered testing whether function being tested throws expected exception.

i know can this:

try{   tested_function($expression->beingtestedthatwillthrowanexception()); }catch ($exception){    if($exception instanceof myexpectedexception){      echo 'ok';    } else {      echo 'failed';    } } 

but i'd wish don't have write try ... catch block everytime, want put in tester class method.

but when this

class tester {    /**     * @param mixed expression evaluate     * @param string expected exception class name     */    public function assertexception($expression, $expectedexception){      try{        $expression;      } catch ($ex) {        if(is_subclass_of($ex, $expectedexception)){          echo 'ok';        } else {          echo 'failed';        }      } 

this fails, because $expression evaluated in moment of method call, before program enters try block.

the other way tried use eval , passing $expression string:

class tester {    /**     * @param string expression evaluate     * @param string expected exception class name     */    public function assertexception($expression, $expectedexception){      try{        eval($expression);      } catch ($ex) {        if(is_subclass_of($ex, $expectedexception)){          echo 'ok';        } else {          echo 'failed';        }      } 

this ok, not allow me use variables main scope, example line fails $test->assertexception('$d->divideby(0);'); because don't have $d variable in tester::assertexception() scope.

should declare all possible variable names global?

how can force expression evaluated within method (or in other way achieve desired result)?

i know there ready-to-use unit testers (phpunit, simpletest etc.) desiring make myself.

you can pass anonymous function (closure) $expression, , bind variables using use keyword - http://php.net/manual/en/functions.anonymous.php

sorry poor english, hope it's understandable.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -