dowy77780 2013-03-01 19:16
浏览 14
已采纳

这是测试已发布变量存在的正确方法吗?

If a query maybe be optionally run as a get() or a post(), so that $id = $_POST['id'] maybe get a null value, are any of these a good practice way to test for the possibly posted variable's existence.

if (!empty($_POST['id'])){ $id = $_POST['id'];}else{$id = FALSE;}

if (isset($_POST['id'])){ $id = $_POST['id'];}else{$id = FALSE;}

$id = isset($_POST['id']) ? $_POST['id'] : FALSE;

or is there some other preferred method? They all do a $_REQUEST() twice which inclines me to think there could be a better way.

Thanks!

  • 写回答

5条回答 默认 最新

  • dongxiezhuo8852 2013-03-01 19:32
    关注

    I would go with:

    $id = isset($_POST['id']) && strlen($_POST['id']) > 0 ? (int)$_POST['id'] : FALSE;
    

    First it checkes if the var is set, and then check if the length is longer than 0.

    In my opinion it is the best readable, as you dont need 5 lines of code if you indent it correctly, what makes it harder to read and makes your file longer:

     if (isset($_POST['id'])){ 
       $id = $_POST['id'];
     }else{
       $id = FALSE;
     }
    

    And if you use $_POST for a simple thing as an ID, just cast it to an int with (int)$_POST['id']. That way you are sure to have a number.

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

报告相同问题?

悬赏问题

  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?