V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
kmvan
V2EX  ›  PHP

不启用的选项值,设定为 -1 好还是 0 好?

  •  
  •   kmvan · 2015-02-13 21:31:25 +08:00 · 2838 次点击
    这是一个创建于 3353 天前的主题,其中的信息可能已经有所发展或是发生改变。

    例如默认值为“不启用”,那么这个 value 设定为 -1 还是 0 比较好?

    <?php
    $default_enable = -1 // or 0?
    $checked = $default_enable === -1 ? ' checked ' : null; // or === 0?
    ?>
    <input type="checkbox" value="<?php echo $default_enable;?>"  <?php echo $checked;?> />
    
    9 条回复    2015-02-14 06:20:34 +08:00
    abelyao
        1
    abelyao  
       2015-02-13 21:57:00 +08:00
    删了 < 0,禁用 = 0,可用 > 0
    目前几个项目都啥这样表示,其实怎样都好,全项目统一就好
    suliuyes
        2
    suliuyes  
       2015-02-13 22:12:09 +08:00
    跟楼上一样。一般我是,0和1表示开关,0是关闭禁用,1是启用,-1表示删除之类的不可用状态。
    lujiajing1126
        3
    lujiajing1126  
       2015-02-13 22:43:47 +08:00
    默认值一般是0
    可以参考FLAGS系统
    icedx
        4
    icedx  
       2015-02-13 22:44:54 +08:00
    一般都是0
    yksoft1
        5
    yksoft1  
       2015-02-13 23:53:48 +08:00
    习惯使用C/C++的,禁用肯定会定义于0
    miaoever
        6
    miaoever  
       2015-02-13 23:59:30 +08:00
    用 0 可以用 unsigned int 存储, -1 就只能是 signed int 了。
    lincanbin
        7
    lincanbin  
       2015-02-14 01:06:40 +08:00
    0

    如果你用0的话,你可以这么写:
    $checked = $default_enable ? ' checked ' : null;

    不过你为什么不用bool呢?
    lincanbin
        8
    lincanbin  
       2015-02-14 01:10:00 +08:00
    PHP官方指定了true=1, false=0
    echo intval(false);//0
    echo intval(true);//1

    所以你可以这样:
    <?php
    $default_enable = 0;
    $checked = $default_enable ? ' checked ' : null;
    ?>
    <input type="checkbox" value="<?php echo $default_enable;?>" <?php echo $checked;?> />

    也可以这样:
    <?php
    $default_enable = false;
    $checked = $default_enable ? ' checked ' : null;
    ?>
    <input type="checkbox" value="<?php echo intval($default_enable); ?>" <?php echo $checked; ?> />
    ryd994
        9
    ryd994  
       2015-02-14 06:20:34 +08:00
    @miaoever 不差这点吧……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2931 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:56 · PVG 10:56 · LAX 19:56 · JFK 22:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.