Why can't I use $app in called function for Slim?

TruMan1 picture TruMan1 · Jul 28, 2013 · Viewed 7.6k times · Source

I am trying to make a reusable function, but everytime I try to use $app in the remote function, I get a blank screen. Here is what does work:

$app = new \Slim\Slim();

//GET CHAPTERS
$app->get(
    '/chapters',
    function () use ($app) {
        $app->contentType('application/json');
        executeSql('SELECT * FROM chapters ORDER BY id');
    }
);

//GENERIC SQL EXECUTE
function executeSql($sql) {
    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() .'}}'; 
    }
}

But I am trying to move the json header in the function and can't get this to work (gets the blank white screen):

$app = new \Slim\Slim();

//GET CHAPTERS
$app->get(
    '/chapters',
    function () {
        executeSql('SELECT * FROM chapters ORDER BY id');
    }
);

//GENERIC SQL EXECUTE
function executeSql($sql) use ($app) {
        $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() .'}}'; 
    }
}

Is something wrong with my syntax or how I'm using PHP? I also tried without the "use ($app)" at all but still same problem.

Answer

corysus picture corysus · Sep 30, 2013

Easy way to fix this is to use getInstance();

function yourFunction(){
   $app = \Slim\Slim::getInstance();
}