PHP boolean operators work like javascript?

One of the things that I like most about JavaScript is that logical operators are very powerful:

  • && can be used to safely retrieve the value of an object field and will return null if either the object or the field was not initialized

    // returns null if param, param.object or param.object.field
    // have not been set
    field = param && param.object && param.object.field;
    
  • || can be used to set default values:

    // set param to its default value
    param = param || defaultValue;
    

Does PHP support this use of logical operators?

+6
source share
4 answers

PHP returns trueor false. But you can emulate JavaScript r = a || b || cwith:

$r = $a ?: $b ?: $c;

Regarding "ands," something like:

$r = ($a && $a->foo) ? $a->foo->bar : null;
+12
source

PHP : .

, :

$result = $a && $b;

$result : true false - $a $b.

+8

, .

+2

:

ANDing PHP , JavaScript, , :

<?php
    // prelim
    $object = new stdClass;
    $object->field = 10;
    $param = new stdClass;
    $param->object = $object;

    // ternary variant     
    $field = !($param && $param->object)?:  $param->object->field;
    echo $field,"\n";

    // alternative to ANDing
    $field = get_object_vars( $param->object )["field"] ?? null;
    echo $field,"\n";

"Elvis" "?:" $, . , $ param , $param->, NOT ("!"), .

You can also perform the task of obtaining field data without ANDing using the get_object_vars()"??" operator in PHP 7 in tandem with get_object_vars().

0
source

All Articles