development

PHP에 단락 평가가 있습니까?

big-blog 2020. 11. 18. 09:20
반응형

PHP에 단락 평가가 있습니까?


다음 코드가 주어집니다.

if (is_valid($string) && up_to_length($string) && file_exists($file)) 
{
    ......
}

경우 is_valid($string)반환 false, PHP 인터프리터는 여전히, 나중에 조건을 같이 확인 않습니다 up_to_length($string)?
그렇다면 왜 필요하지 않은데 추가 작업을 수행합니까?


예, PHP 인터프리터는 "지연"입니다. 즉, 조건을 평가하기 위해 가능한 최소한의 비교를 수행합니다.

이를 확인하려면 다음을 시도하십시오.

function saySomething()
{
    echo 'hi!';
    return true;
}

if (false && saySomething())
{
    echo 'statement evaluated to true';
}

네, 그렇습니다. 단락 평가에 의존하는 작은 트릭이 있습니다. 때로는 삼항으로 작성하고 싶은 작은 if 문이있을 수 있습니다. 예 :

    if ($confirmed) {
        $answer = 'Yes';
    } else {
        $answer = 'No';
    }

다음과 같이 다시 작성할 수 있습니다.

   $answer = $confirmed ? 'Yes' : 'No';

그러나 yes 블록이 일부 기능을 실행해야한다면 어떻게 될까요?

    if ($confirmed) {
        do_something();

        $answer = 'Yes';
    } else {
        $answer = 'No';
    }

글쎄요, 단락 평가 때문에 삼항으로 다시 쓰는 것은 여전히 ​​가능합니다.

    $answer = $confirmed && (do_something() || true) ? 'Yes' : 'No';

이 경우 표현식 (do_something () || true)는 삼항의 전체 결과를 변경하는 데 아무 작업도하지 않지만 삼항 조건이 유지 true되고의 반환 값을 무시합니다 do_something().


아니요, 첫 번째 조건이 충족되지 않으면 더 이상 다른 조건을 확인하지 않습니다.


비트 연산자&|입니다. 항상 두 피연산자를 모두 평가합니다.

논리 연산자가 있다 AND, OR, &&,와 ||.

  • 네 명의 연산자는 모두 필요한 경우에만 오른쪽을 평가합니다.
  • AND그리고 OR보다 낮은 우선 순위를 가지고 &&||. 아래 예를 참조하십시오.

 

PHP 매뉴얼에서 :

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;

이 예에서, e될 것입니다 truef있을 것입니다 false.


내 연구에 따르면 PHP는 &&JavaScript 와 동일한 단락 연산자 를 가지고 있지 않은 것 같습니다 .

이 테스트를 실행했습니다.

$one = true;

$two = 'Cabbage';

$test = $one && $two;

echo $test;

그리고 PHP 7.0.8 반환 1하지 Cabbage.


내 자신의 단락 평가 논리를 만들었습니다. 불행히도 자바 스크립트 빠른 구문과는 다르지만 아마도 이것은 유용 할 수있는 솔루션 일 것입니다.

$short_circuit_isset = function($var, $default_value = NULL) {
    return  (isset($var)) ? : $default_value;
};

$return_title = $short_circuit_isset( $_GET['returntitle'], 'God');

// Should return type 'String' value 'God', if get param is not set

나는 내가 다음 논리를 어디서 얻었는지 기억할 수 없지만 다음을 수행하면;

(isset($var)) ? : $default_value;

물음표 뒤에 참 조건 변수를 다시 작성하지 않아도됩니다. 예 :

(isset($super_long_var_name)) ? $super_long_var_name : $default_value;

매우 중요한 관찰로 삼항 연산자를 이런 방식으로 사용할 때 비교가 이루어지면 단일 변수가 아니기 때문에 해당 비교의 값만 전달된다는 것을 알 수 있습니다. 예 :

$num = 1;
$num2 = 2;
var_dump( ($num < $num2) ? : 'oh snap' );
// outputs bool 'true'

My choice: do not trust Short Circuit evaluation in PHP...

function saySomething()
{
    print ('hi!');
    return true;
}

if (1 || saySomething())
{
    print('statement evaluated to true');
}

The second part in the condition 1 || saySomething() is irrelevant, because this will always return true. Unfortunately saySomething() is evaluated & executed.

Maybe I'm misunderstood the exact logic of short-circuiting expressions, but this doesn't look like "it will do the minimum number of comparisons possible" to me.

Moreover, it's not only a performance concern, if you do assignments inside comparisons or if you do something that makes a difference, other than just comparing stuff, you could end with different results.

Anyway... be careful.


Side note: If you want to avoid the lazy check and run every part of the condition, in that case you need to use the logical AND like this:

if (condition1 & condition2) {
 echo "both true";
}
else {
 echo "one or both false";
}

This is useful when you need for example call two functions even if the first one returned false.

참고URL : https://stackoverflow.com/questions/5694733/does-php-have-short-circuit-evaluation

반응형