Bug #70618 [Opn->Nab]: Ternary eccentricity

From: Date: Fri, 02 Oct 2015 00:32:08 +0000
Subject: Bug #70618 [Opn->Nab]: Ternary eccentricity
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-196340@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=70618&edit=1

 ID:                 70618
 Updated by:         requinix@php.net
 Reported by:        symphonymous at hotmail dot com
 Summary:            Ternary eccentricity
-Status:             Open
+Status:             Not a bug
 Type:               Bug
-Package:            PHP Language Specification
+Package:            Scripting Engine problem
 Operating System:   Ubuntu
 PHP Version:        5.6.14RC1
 Block user comment: N
 Private report:     N

 New Comment:

Eccentric yes, bug no. Backwards compatibility is the biggest hurdle, so if it were to change in the
future then it would likely be made non-associative (ie. parentheses would be required). Besides,
parentheses also help to make it explicit to the reader about how the logic works.

There was a discussion about this a while back: http://markmail.org/thread/5bjy2xnu2vrgxxmy


Previous Comments:
------------------------------------------------------------------------
[2015-10-01 21:42:37] symphonymous at hotmail dot com

Description:
------------
I suspect this is a bug as the behaviour is a little worrying.

I was using the following in a Laravel program

    $fieldLabel = // has a field label been manually defined
      ($fieldLabel =  $this->hasAttribute($fieldValue, 'FieldLabel'))
      ? $fieldLabel
      : ($this->parseFieldType($fieldValue) != 'hidden')         
        ? ucfirst($fieldKey)
        : '';

However when $label was defined it was resolving to 
$fieldLabel = ucfirst($fieldKey); 

(ie. the second ternary).

the resolution was to parenthesise the second ternary (which I should have done in the first place):

    $fieldLabel = // has a field label been manually defined
      ($fieldLabel =  $this->hasAttribute($fieldValue, 'FieldLabel'))
      ? $fieldLabel
      : (($this->parseFieldType($fieldValue) != 'hidden')         
        ? ucfirst($fieldKey)
        : '');

The bug, in my eyes, is that aforementioned code should have thrown an exception as the ternary
statement gave an ambiguous result.

best

Jon

Test script:
---------------
// here is the same issue again in a simpler form, tested with 
// "php artisan tinker"

$foo = 1;

$bar = ($bar = $foo) ? $bar : ($bar = 2) ? 2 : 'null';

Expected result:
----------------
either an exception as the statement is ambiguous or 1;

I would suggest the former.

Actual result:
--------------
2


------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=70618&edit=1


Thread (1 message)

  • requinix@php.net
  • Unknown Message
    • requinix@php.net
« previous php.bugs (#196340) next »