函數計算PHP 變量不存在無法引用和判斷的解決方案

最近研究了函數計算,很不錯的服務,總結一個php存在的一個問題,爲以後的小白們避免同樣的錯誤。


<?php
use RingCentral\Psr7\Response;

function initializer($context) {
    echo 'initializing' . PHP_EOL;
}

function handler($request, $context): Response{
    //$body       = $request->getBody()->getContents();
    $queries    = $request->getQueryParams();
    //$method     = $request->getMethod();
    //$headers    = $request->getHeaders();
    //$path       = $request->getAttribute("path");
    //$requestURI = $request->getAttribute("requestURI");
    //$clientIP   = $request->getAttribute("clientIP");
    
    $params['status'] = 0;

    //如何不存在$queries['id']
    //bug無法判斷不存在的變量

    if($queries['id']){
      $params['status'] = 1;
    }

    $respHeaders = array('Content-Type' => 'application/json');
    $respBody = json_encode($params);
    return new Response(200, $respHeaders, $respBody);
}

解決方案:


$GLOBALS['queries'] = $queries;
$id = isset($GLOBALS['queries']['id'])?$GLOBALS['queries']['id']:'';
if($id){
    $params['status'] = 1;
}


利用$GLOBALS來解決,isset判斷

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章