您现在的位置是:首页 > PHP学习

李清波 2019-07-17 PHP学习 1701 复制当前网址

PHP新手要学会用静态方法可以提升开发效率

我也是前几年才慢慢使用静态方法,但发现使用上一次以后开始上瘾了,下面我们以thinkphp5.1框架来作为演示


这是一个module文件UserModel.php

namespace app\admin\model;
use think\Model;
use think\Db;

class UserModel extends Model
{
    protected $name = 'user';
    protected $pk = 'id';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    //用户状态
    const STATUS_A = 1;
    const STATUS_B = 2;
    

    public static function a(){
        echo 'a';
    }

    public static function b(){
        return 'b';
    }
}


User.php文件调用

namespace app\admin\controller;
use app\admin\model\UserModel;

use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Request;

class User extends Controller {

    public function index(){
        UserModel::a();
        UserModel::b();
    }


}


这样就可以省去实例化,等熟练之后,我们发现通过调用静态方法和静态变量操作起来特别方便,也提升了不少开发效率,写起代码来也很飘逸。

以上的示例也只是皮毛而已,希望新手们多多学习和练习。

文章来源:https://www.liqingbo.com/blog-1542.html

评论