我也是前几年才慢慢使用静态方法,但发现使用上一次以后开始上瘾了,下面我们以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();
}
}这样就可以省去实例化,等熟练之后,我们发现通过调用静态方法和静态变量操作起来特别方便,也提升了不少开发效率,写起代码来也很飘逸。
以上的示例也只是皮毛而已,希望新手们多多学习和练习。