Why can't I use $app in called function for Slim?
You could always pass the $app object as an argument to your function.
$app = new \Slim\Slim();//GET CHAPTERS$app->get( '/chapters', function () use ($app) { executeSql($app, 'SELECT * FROM chapters ORDER BY id'); });//GENERIC SQL EXECUTEfunction executeSql(\Slim\Slim $app, $sql) { $app->contentType('application/json'); try { $db = getConnection(); $stmt = $db->query($sql); $results = $stmt->fetchAll(PDO::FETCH_OBJ); $db = null; echo json_encode($results); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; }}
It is cleaner to keep database calls and app logic/presentation separate. I would return your "chapters" object immediately and handle anything else outside of the executeSql function.
$app = new \Slim\Slim();// GET CHAPTERS$app->get('/chapters', function () use ($app) { $app->contentType('application/json'); $chapters = executeSql('SELECT * FROM chapters ORDER BY id'); if ($chapters) { $app->response->setStatus(200); echo json_encode($results); } else { $app->response->setStatus(400); echo '{"error":{"text":"error getting chapters"}}'; }});// GENERIC SQL EXECUTEfunction executeSql($sql) { try { $db = getConnection(); $stmt = $db->query($sql); $results = $stmt->fetchAll(PDO::FETCH_OBJ); $db = null; return $results; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; }}