dongyongju9560 2018-06-04 07:45
浏览 80
已采纳

如果属性不存在,则显示空字符串

In the lower versions of php I used to use the following code to show object property in the page :

  <input type=text value='<?php echo $obj->title ;?>'>

In the edit mode $obj was an object fetched from database and user could see the already existed value, and for insert mode there was no $obj because there was no $_GET["obj_id"] and $obj wasn't defined so the input field was shown empty ,

In the new versions php stops the insert pages because $obj isn't defined or has no property named title , So I should use something like this :

<input type=text value='<?php echo isset($obj)?$obj->title:"" ;?>'>

Now what I want to do is to make this some shorten, I created a function like the following but it doesn't seem to work and keeps showing the error,

function showprop($obj,$prop)
{
if( isset($obj) )
 echo $obj->{$prop};
else
 echo "";
}

<input type=text value='<?php showprop($obj,"title");?>'>

Any suggestion to make this work without getting notice? Thanks in advance

  • 写回答

2条回答 默认 最新

  • drtldt55533 2018-06-04 07:49
    关注

    A function is not going to work, since PHP will try to resolve $obj before passing its value into the function, so you're left with the same problem.

    Use the null coalescing operator instead (available from PHP 7):

    <?= $obj->title ?? '' ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?