PHP ternary operator vs null coalescing operator

后端 未结 13 1708
南笙
南笙 2020-11-22 15:58

Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave d

13条回答
  •  情话喂你
    2020-11-22 16:38

    class a
    {
        public $a = 'aaa';
    }
    
    $a = new a();
    
    echo $a->a;  // Writes 'aaa'
    echo $a->b;  // Notice: Undefined property: a::$b
    
    echo $a->a ?? '$a->a does not exists';  // Writes 'aaa'
    
    // Does not throw an error although $a->b does not exist.
    echo $a->b ?? '$a->b does not exist.';  // Writes $a->b does not exist.
    
    // Does not throw an error although $a->b and also $a->b->c does not exist.
    echo $a->b->c ?? '$a->b->c does not exist.';  // Writes $a->b->c does not exist.
    

提交回复
热议问题