鍍金池/ 問(wèn)答/PHP/ (static::model)::count($conditions);請(qǐng)問(wèn)這種

(static::model)::count($conditions);請(qǐng)問(wèn)這種寫法有什么弊端嗎

問(wèn)題描述

(static::model)::count($conditions); // 請(qǐng)問(wèn)這種寫法有什么弊端嗎

相關(guān)代碼

trait SRV {

    public static function count(array $conditions) {
        if (empty(static::model)) {
            return 0;
        }
        return (static::model)::count($conditions);
    }

}

class CommentSrv {

    // DB靜態(tài)類
    const model = CommentDB::class;

    use SRV;
}

上面的代碼在實(shí)際應(yīng)用中可以正常使用,但是這種寫法,我沒有搜索到,不知道會(huì)不會(huì)產(chǎn)生什么后遺癥..導(dǎo)致后期維護(hù)成本提高

回答
編輯回答
她愚我

主要是可讀性差,要知道程序開發(fā)的難點(diǎn)是便于長(zhǎng)期維護(hù),而不是圖代碼簡(jiǎn)短

2017年9月17日 14:51
編輯回答
維他命

嘗試些新東西很好啊,寫的東西搜不到也很正常啊
這意思不就是 return CommentDB::count($conditions);
你換成抽象類還不是可以

2017年4月5日 01:36
編輯回答
未命名

確定可以運(yùn)行? 表示懷疑呢.
以前倒是想這樣弄,但是Model::class是一個(gè)字符串, STR::count();這得報(bào)錯(cuò)啊. (至少曾經(jīng)這樣做的時(shí)候是報(bào)錯(cuò)了滴.

2018年8月12日 18:04
編輯回答
神經(jīng)質(zhì)
trait SRV {
    /**
     * 統(tǒng)計(jì)數(shù)據(jù)量
     *
     * @param array $conditions 檢索條件 具體處理在父類 buildCondition
     * @return int
     */
    public static function count(array $conditions) {
        $model = self::getModel();
        if (is_null($model)) {
            return 0;
        }
        return $model::count($conditions);
    }

    /**
     * 獲取數(shù)據(jù)模型
     *
     * @return string || null
     */
    private static function getModel() {

        if (empty(static::$model)) {
            $parentClassName = get_class();

            if (!empty($parentClassName)) {
                $modelName = str_replace(['Srv', 'SRV'], 'DB', $parentClassName);
            }
        } else {
            $modelName = static::$model;
        }

        if (!class_exists($modelName)) {
            return null;
        }

        return $modelName;
    }
}

之前那種寫法可能php7以下不兼容,雖然已經(jīng)不考慮兼容7以下,但是那種寫法始終有點(diǎn)不放心,還是換這種吧...

2018年1月10日 20:15