dthtvk3666 2013-07-03 17:48
浏览 36
已采纳

PHP变量声明速记(类似于JavaScript)

In JavaScript, I can do this:

var somevar = {
    propertyTwo : false,
    propertyThree : "hello!"
}

var test = somevar.propertyOne || somevar.propertyTwo || somevar.propertyThree

alert(test); //displays "hello!"

Is there a similar functionality in PHP for this? Haven't been able to find anything online.

I tried this, but PHP just treats it like a comparison and echo's 1 (true)

$somevar = array(
    'propertyTwo' => false,
    'propertyThree' => "hello!"
);

$test = $somevar['propertyOne'] || $somevar['propertyTwo'] || $somevar['propertyThree'];

echo $test; //displays '1'

Not really a big deal if there isn't, but I figured that with all of the bells and whistles provided in php 5.x, there would be some kind of shorthand for assigning the first true value in a list of values to a single variable like that.

I suppose I could write a function.

EDIT :

As I suspected, PHP doesn't have the same quirk.

Quick function I wrote

function assign_list($list){
foreach($list as $v)
    if(isset($v) && $v) return $v;
return false;
}

Just pass it an array of stuff

  • 写回答

2条回答 默认 最新

  • duanni5726 2013-07-03 17:54
    关注

    The following will work in PHP >= 5.3, but you will still receive a Notice Error because propertyOne is not defined.

    <?php
    $somevar = array(
        'propertyTwo' => false,
        'propertyThree' => "hello!"
    );
    
    $test = $somevar['propertyOne'] ?: $somevar['propertyTwo'] ?: $somevar['propertyThree'];
    
    echo $test; //displays 'hello!'
    

    You could however work around this by supressing the variables, but it is highly unrecommended:

    $test = @$somevar['propertyOne'] ?: @$somevar['propertyTwo'] ?: @$somevar['propertyThree'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据