<?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
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 thetry()
block and that's a whole other story but I also had to rewrite the wholeopenDatabaseConnection()
function.You must to define $db out of
try
to use it incatch
!If you define $db out of function you need to global it in function with this :