douchuo0730 2018-05-01 15:50
浏览 21
已采纳

变量分配和检查

Can Someone tell me what's wrong with this code

function someFunction($num=null) {
  return $num;
}
if ($name = someFunction('mystr') && $name ) {
 echo 'hello ';
}else {
  echo 'hi';
}

Why it is going in else condition and giving me notice of undefined variable $name

Edited: - if i do like this

if($name = someFunction() && $name ){
   echo 'hello';
} else {
   echo 'hi';
}

this time its also going on else condition as it should but it also not showing the error as i understand it, php just check my first condition $name = someFunction() and its fail then just else

but if i do as i do previously $name = someFunction('str') now $name is set so why notice of undefined variable

sorry for bad grammer

just want to know what is happening here.

  • 写回答

3条回答 默认 最新

  • dongyou9373 2018-05-01 16:05
    关注

    It's because logical operators like && have higher precedence than the assignment operator =. You can read more about this here: http://php.net/manual/en/language.operators.precedence.php

    The line

    if ($name = someFunction('mystr') && $name ) {
    

    is being evaluated like this:

    if ($name = (someFunction('mystr') && $name) ) {
    

    where the expression in the inner brackets is evaluated first. Because $name has not been defined before this point, a notice is raised.

    I think what you're trying to do is this:

    if (($name = someFunction('mystr')) && $name ) {
    

    where you assign the value mystr to $name and then also evaluate that it's "truthy". But as pointed out in the comments, this is a bit of a strange approach. The following code would be equivalent:

    $name = 'mystr';
    
    if ($name) {
      ...
    

    This feels a bit like a problem that's been cut down a bit too much in order to explain it, because it's not really clear why you're doing this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错