Do PHP's logical operators work as JavaScript's?

六月ゝ 毕业季﹏ 提交于 2020-06-10 17:42:22

问题


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

  • && can be used to safely extract the value of an object's field, and will return null if either the object or the field has not been 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 allow this use of the logical operators as well?


回答1:


PHP returns true orfalse. But you can emulate JavaScript's r = a || b || c with:

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

Regarding 'ands', something like:

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



回答2:


PHP logical operators do not return the value on any of their sides : they will always get you a boolean.

For instance, doing :

$result = $a && $b;

Will always make $result contain a boolean : true or false -- and never $a nor $b.




回答3:


You can set up similar functionality using ternary operators.




回答4:


Revised:

With respect to logical ANDing in PHP to achieve the same kind of result as JavaScript, you could use a variant of the traditional ternary, as follows:

<?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";

See live code

The "Elvis" operator "?:" only assigns the result to $field if the conditional expression is false. So, if $param exists as well as $param->object, then you have to use the NOT operator ("!") in order to get the desired result.

You may also accomplish the objective of getting the field data without ANDing by utilizing the null coalescing operator ("??") in PHP 7 in tandem with get_object_vars().



来源:https://stackoverflow.com/questions/5278506/do-phps-logical-operators-work-as-javascripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!