skip to Main Content
    <?php    
    public function run() {
    try {
        $db = $this->openDatabaseConnection();
        $this->dispatchToController($db);
    }
    catch(AccessDeniedException $e) {
        require_once 'app/controller/error.php';
        $controller = new ErrorController($db);
        $controller->accessDenied();
    }
    catch(NotFoundException $e) {
        require_once 'app/controller/error.php';
        $controller = new ErrorController($db);
        $controller->notFound();
    }
    catch(Exception $e) {
        if(PRODUCTION) {
        require_once 'app/controller/error.php';
        $controller = new ErrorController($db);
        $controller->unknown();
        }
        
    }
}

the $db is defined on top, the snippet was run on ngnix web server with PHP 7.4.33 and gave the following error [500]: GET / - Uncaught ErrorException: Undefined variable: db

2

Answers


  1. Chosen as BEST ANSWER
    public function run() {
        $db = $this->openDatabaseConnection();
        $this->dispatchToController($db);
    
        catch(AccessDeniedException $e) {
            require_once 'app/controller/error.php';
            $controller = new ErrorController($db);
            $controller->accessDenied();
        }
        catch(NotFoundException $e) {
            require_once 'app/controller/error.php';
            $controller = new ErrorController($db);
            $controller->notFound();
        }
        catch(Exception $e) {
            if(PRODUCTION) {
            require_once 'app/controller/error.php';
            $controller = new ErrorController($db);
            $controller->unknown();
            }
            
        }
    }
    

    the solution was simple, in PHP you either have to make the variable global or use it outside of blocks for another block to access it, so I got $db outside of the try() block and that's a whole other story but I also had to rewrite the whole openDatabaseConnection() function.


  2. You must to define $db out of try to use it in catch !

    If you define $db out of function you need to global it in function with this :

    global $db , $anyname;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search