考虑这个jQuery语句
isTouch = document.createTouch !== undefined
我想知道我们是否在PHP中有类似的语句,不是isset(),而是从字面上检查未定义的值,例如:
$isTouch != ""
是否有与上述PHP类似的东西?
考虑这个jQuery语句
isTouch = document.createTouch !== undefined
我想知道我们是否在PHP中有类似的语句,不是isset(),而是从字面上检查未定义的值,例如:
$isTouch != ""
是否有与上述PHP类似的东西?
Answers:
您可以使用 -
$isTouch = isset($variable);
true如果$variable定义了,它将返回。如果未定义变量,它将返回false。
注意:如果var存在并且具有非NULL的值,则返回TRUE,否则返回FALSE。
如果要检查false,0则可以使用empty()-
$isTouch = empty($variable);
empty() 效劳于 -
isset()总是返回布尔值。
true或false。因此,不需要那种转换。
empty()如果它为空字符串,则返回false。isset()如果其为空字符串,则将返回true;如果内部也进行了isset检查,则其也为true。
$isTouch = (bool) $variable;与效果相同,isset()也许会更好一点,因为它的工作方式类似于empty()。
要检查是否设置了变量,需要使用isset函数。
$lorem = 'potato';
if(isset($lorem)){
echo 'isset true' . '<br />';
}else{
echo 'isset false' . '<br />';
}
if(isset($ipsum)){
echo 'isset true' . '<br />';
}else{
echo 'isset false' . '<br />';
}
此代码将打印:
isset true
isset false
您可以使用 -
三元操作员检查通过POST / GET设置的Wheater值或不这样
$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : '';
$value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : '';
$value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : '';
$value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';
JavaScript的“严格不等于”运算符(!==)与比较undefined并不会导致false对null值。
var createTouch = null;
isTouch = createTouch !== undefined // true
要在PHP中实现等效行为,可以检查的结果键中是否存在变量名称get_defined_vars()。
// just to simplify output format
const BR = '<br>' . PHP_EOL;
// set a global variable to test independence in local scope
$test = 1;
// test in local scope (what is working in global scope as well)
function test()
{
// is global variable found?
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test does not exist.
// is local variable found?
$test = null;
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test exists.
// try same non-null variable value as globally defined as well
$test = 1;
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test exists.
// repeat test after variable is unset
unset($test);
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.') . BR;
// $test does not exist.
}
test();
在大多数情况下,isset($variable)是适当的。那等于array_key_exists('variable', get_defined_vars()) && null !== $variable。如果您使用时null !== $variable没有预先检查其是否存在,则会在日志中添加警告,因为这是尝试读取该值的尝试未定义变量。
但是,您可以将未定义的变量应用于引用,而不会出现任何警告:
// write our own isset() function
function my_isset(&$var)
{
// here $var is defined
// and initialized to null if the given argument was not defined
return null === $var;
}
// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable); // $is_set is false
if(isset($variable)){
$isTouch = $variable;
}
要么
if(!isset($variable)){
$isTouch = "";//
}