PHP-변수가 정의되지 않았는지 확인


87

이 jquery 문장을 고려하십시오.

isTouch = document.createTouch !== undefined

PHP에 비슷한 문이 있는지 알고 싶습니다. isset ()이 아니라 문자 그대로 정의되지 않은 값을 확인합니다.

$isTouch != ""

PHP에서 위와 비슷한 것이 있습니까?


답변:


167

당신이 사용할 수있는 -

$isTouch = isset($variable);

가 정의 되면 반환 true됩니다 $variable. 변수가 정의되어 있지 않으면을 반환 false합니다.

참고 : var가 있고 NULL이 아닌 값이 있으면 TRUE를 반환하고 그렇지 않으면 FALSE를 반환합니다.

당신이 확인하고 싶은 경우 false, 0등 그런 다음 사용할 수 있습니다 empty()-

$isTouch = empty($variable);

empty() 작동-

  • "" (빈 문자열)
  • 0 (정수로 0)
  • 0.0 (부동 수로 0)
  • "0" (0은 문자열)
  • 없는
  • 그릇된
  • array () (빈 배열)
  • $ var; (선언되었지만 값이없는 변수)

1
isset()항상 bool을 반환합니다.
VeeeneX

부울 캐스트가 필요합니까? isset (...) 이미 bool을 반환합니까?
Cr3aHal0

1
아니요 . true또는 false. 따라서 캐스팅이 필요하지 않습니다.
Sougata Bose

1
empty()빈 문자열이면 false를 반환하는를 사용하여이 작업을 수행 할 수도 있습니다 . isset()빈 문자열이면 true를 반환하고 내부적으로 isset 검사를 수행합니다.
mic

1
당신은 또한 이것을 할 수 있습니다 : $isTouch = (bool) $variable;이것은 . isset()와 같이 작동하기 때문에 약간 더 낫습니다 empty().
mic

19

또 다른 방법은 간단합니다.

if($test){
    echo "Yes 1";
}
if(!is_null($test)){
    echo "Yes 2";
}

$test = "hello";

if($test){
    echo "Yes 3";
}

반환됩니다 :

"Yes 3"

가장 좋은 방법은 isset ()을 사용하는 것입니다. 그렇지 않으면 "undefined $ test"와 같은 오류가 발생할 수 있습니다.

다음과 같이 할 수 있습니다.

if( isset($test) && ($test!==null) )

첫 번째 조건이 허용되지 않기 때문에 오류가 발생하지 않습니다.


$test!==null대괄호없이 사용하면 어떻게 될까요? 오류가 발생합니까?
Vir

아니, 그것도 괜찮아.
TiDJ


6

당신이 사용할 수있는 -

POST / GET에 의해 설정된 값을 확인하는 삼항 oprator 또는 이와 같은 것이 아닙니다.

$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'] : '';

3

비교시 JavaScript의 '엄격하지 않음'연산자 ( !==) 는 값에 영향 을 undefined주지 않습니다 .falsenull

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

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.