$p = (isset($_REQUEST["p"])?$_REQUEST["p"]:"");
Run Code Online (Sandbox Code Playgroud)
这是我在php代码中常用的常用行.我总是假设有更好的(小而快的)写同样的方法吗?
Ael*_*ios 17
创建自己的功能:
function getIfSet(&$value, $default = null)
{
return isset($value) ? $value : $default;
}
$p = getIfSet($_REQUEST['p']);
Run Code Online (Sandbox Code Playgroud)
没有其他清洁解决方案.
你想要的更短吗?
当然,如果您每次访问请求值时都使用它,则应该在某处创建一个函数,然后使用它:
function reqVal( $val, $default = "", $no_sql = true )
{
$var = isset( $_REQUEST[$val] ) ? $_REQUEST[$val] : $default;
$var = $no_sql ? nosql( $var ) : $var;
return $var;
}
function getVal( $val, $default = "", $no_sql = true )
{
$var = isset( $_GET[$val] ) ? $_GET[$val] : $default;
$var = $no_sql ? nosql( $var ) : $var;
return $var;
}
function postVal( $val, $default = "", $no_sql = true )
{
$var = isset( $_POST[$val] ) ? $_POST[$val] : $default;
$var = $no_sql ? nosql( $var ) : $var;
return $var;
}
Run Code Online (Sandbox Code Playgroud)
现在添加sql注入检查:
function nosql( $var )
{
if ( is_array( $var ) ) {
foreach ( $var as $key => $elem ) $var[$key] = nosql( $elem );
} else if ( $var === null ) {
return null;
} else {
if ( get_magic_quotes_gpc() ) $var = stripslashes( $var );
$var = mysql_real_escape_string( $var );
}
return $var;
}
Run Code Online (Sandbox Code Playgroud)
并且访问它总是这样简单:
$p = reqVal( 'p', 0 );
$p = getVal( 'p', 'something', false );
$p = postVal( 'p' ); // or just forget the 2nd and 3rd parameter
Run Code Online (Sandbox Code Playgroud)
编辑:PHP 7 添加了一个空合并运算符(“??”)
$p = $_REQUEST["p"] ?? '';
Run Code Online (Sandbox Code Playgroud)
https://www.php.net/manual/en/migration70.new-features.php
原来的:
如果你想要更短的东西,并且满足于一个空的(字符串)默认值,下面的工作:
$p = @$_REQUEST['p'];
Run Code Online (Sandbox Code Playgroud)
@ 是错误抑制运算符,如果未设置该值,它将阻止表达式发出警告。
http://www.php.net/manual/en/language.operators.errorcontrol.php
| 归档时间: |
|
| 查看次数: |
21515 次 |
| 最近记录: |