前端表格編輯時總是要做一些檢測,是否欄位是 checked, selected, disabled, readonly 等等狀態。假若我們要查 checkbox 欄位是否被選中並加上 checked 時,只要加這段方程式碼就好了。

<input type="checkbox" name="myname" value="1" <?php checked('1','我的value')?> />

原函數如下:

function checked( $checked, $current = true, $echo = true ) {
    return __checked_selected_helper( $checked, $current, $echo, 'checked' );
}

function selected( $selected, $current = true, $echo = true ) {
    return __checked_selected_helper( $selected, $current, $echo, 'selected' );
}

function disabled( $disabled, $current = true, $echo = true ) {
    return __checked_selected_helper( $disabled, $current, $echo, 'disabled' );
}

function readonly( $readonly, $current = true, $echo = true ) {
    return __checked_selected_helper( $readonly, $current, $echo, 'readonly' );
}

function __checked_selected_helper( $helper, $current, $echo, $type ) {
    if ( (string) $helper === (string) $current ) {
        $result = " $type='$type'";
    } else {
        $result = '';
    }

    if ( $echo ) {
        echo $result;
    } 

    return $result;
}