Hata düzeyi E_NOTICE PHP ile dış değişkenleri (örneğin POST / GET) nasıl kullanılır

2 Cevap php

I E_NOTICE dahil hata seviyesinde PHP ile dış değişkenleri nasıl kullanılacağını en iyi yol arıyorum.

SİZ gibi farklı bir yaklaşım her bazı ipuçları verebilir veya önerebilirsiniz eğer ben üç olası yolu var, ben, mutlu olurdu.

    1.
class WebApp {

    public static function _GET($Index) {
        if (isset($_GET[$Index])) {
            return $_GET[$Index];
        } else {
            return NULL;
        }
    }
}

// E_NOTICE, does not throw a notice:
echo WebApp::_GET('ID');

// E_NOTICE, throws a notice:
echo $_GET['ID'];

2.

class RequestSanitizer {
    const V_INTEGER = 1;
    const V_STRING = 2;
    const V_REAL = 3;

    public static function Sanitize($arr) {
        foreach ($arr as $key => $val) {
            if (array_key_exists($key, $_GET)) {
                switch ($val) {
                    case RequestSanitizer::V_INTEGER:
                        $_GET[$key] = $_GET[$key] + 0;
                        break;
                    case RequestSanitizer::V_STRING:
                        $_GET[$key] = $_GET[$key] + '';
                        break;
                    case RequestSanitizer::V_REAL:
                        $_GET[$key] = $_GET[$key] + 0;
                        break;
                }
            } else {
                $_GET[$key] = null;
            }
        }
    }
}

RequestSanitizer::Sanitize(array(
    'GraphID' => RequestSanitizer::V_INTEGER,  
    'UserName' => RequestSanitizer::V_STRING,  
    'Password' => RequestSanitizer::V_STRING,  
    'Price' => RequestSanitizer::V_REAL 
));

echo $_GET['GraphID'];

3.

if (isset($_GET['ID']) && ($_GET['ID']+0>0)) {
   echo $_GET['ID']
}

2 Cevap

Ben bu yüzden tüm Php "superglobal'leri" saklar ve "param ()", "numParam ()" gibi yöntemler, "arrayParam ()" sağlayan bir istek sınıfını kullanın ve istiyorum.

$req = new Request();
$user_id = $req->numParam('id');
 // user_id is guaranteed to be a valid integer or 0

Ben kullanmak istiyorum

if (isset($_GET['ID']) && ($_GET['ID']+0>0)) {
   echo (int)$_GET['ID']
}

tamsayı bir döküm ile (int). Değer bir tamsayı olması gerekir.