如何在 PHP 中使用错误级别为 E_NOTICE 的外部变量(例如 POST/GET)
我正在寻找如何在 PHP 中使用外部变量的最佳方法,错误级别包括 E_NOTICE
。
我有三种可能的方法,如果您能为每种方法提供一些提示或建议您喜欢的不同方法,我会很高兴。
- 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'] }
I'm looking for the best way how to use external variables in PHP with error level including E_NOTICE
.
I have three possible ways, I would be happy, if you can give some hints on each or suggest a different approach that YOU like.
- 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'] }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将使用
转换为整数
(int)
。如果该值必须是整数。I would use
with a casting to integer
(int)
. If the value must be an integer.我会使用一个 Request 类来封装所有 Php“超全局变量”,并提供“param()”、“numParam()”、“arrayParam()”等方法。
i'd use a Request class that encapsulates all Php "superglobals" and provides methods like "param()", "numParam()", "arrayParam()" and so on.