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

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C