如何理解PHP中的nested ::运算符? [英] How can I understand nested ?: operators in PHP?

查看:72
本文介绍了如何理解PHP中的nested ::运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
PHP三元运算符的问题

Possible Duplicate:
Problem with PHP ternary operator

我在

I was reading up a bit on PHP in this article, and I stopped for a while to consider one of his gripes. I can't figure out how on earth PHP comes to the result that it does.

不同于(从字面上看!)其他所有具有类似运算符的语言,?:是 left 的关联词.因此:

Unlike (literally!) every other language with a similar operator, ?: is left associative. So this:

$arg = 'T';   
$vehicle = ( ( $arg == 'B' ) ? 'bus' :
            ( $arg == 'A' ) ? 'airplane' :
            ( $arg == 'T' ) ? 'train' :
            ( $arg == 'C' ) ? 'car' :
            ( $arg == 'H' ) ? 'horse' :
            'feet' );   
echo $vehicle;

印马.

PHP遵循什么逻辑路径将'horse'分配给$vehicle?

What logical path does PHP follow that results in 'horse' being assigned to $vehicle?

推荐答案

括号是解决修复的解决方案:

Bracketing is the solution for both understanding and fixing:

这应该具有意外结果(horse):

$arg = 'T';  
$vehicle = (
    (
        (
            (
                (
                    ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' )
                ) ? 'airplane' : ( $arg == 'T' )
            ) ? 'train' : ( $arg == 'C' )
        ) ? 'car' : ( $arg == 'H' )
    ) ? 'horse' : 'feet'
);  
echo $vehicle;

这应该具有预期的结果(train):

This should have the indended result (train):

$arg = 'T';   
$vehicle = (
    ( $arg == 'B' ) ? 'bus' : (
        ( $arg == 'A' ) ? 'airplane' : (
            ( $arg == 'T' ) ? 'train' : (
                ( $arg == 'C' ) ? 'car' : (
                    ( $arg == 'H' ) ? 'horse' : 'feet'
                )
            )
        )
    )
);   
echo $vehicle;

这篇关于如何理解PHP中的nested ::运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆