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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度