清晰分辨 PHP 真静态与假静态

我给你分的清清楚楚、一眼分清「真静态 / 假静态」,

你以后看到 :: 立马就能分辨,绝不混。

 

---

一、先定义

1. 真静态方法 👉 源码带 static

只能用:类名::方法()

不能用 -> 调用

2. 假静态方法(TP 模型专属)

源码没有 static

是 ThinkPHP 魔术方法代理

模型::where() 本质 = (new 模型)->where()

 

---

二、你要的:【真静态::方法】大全

1. 纯 Db 类 全部都是真静态

Db::name()

Db::table()

Db::raw()

Db::transaction() // 事务

Db::beginTrans()

Db::commit()

Db::rollback()

Db::count()

Db::max()

✅ 全是 public static function

正宗双冒号调用。

 

---

2. 模型 Model 里 自带的真静态(不是 where 那些)

这些是正经 static,和 Db 一模一样:

// 场景:查询单条

User::get()

 

// 场景:查询多条

User::all()

 

// 缓存、实例化

User::instance()

 

// 软删除、全局范围

User::withTrashed()

User::onlyTrashed()

 

// 快速创建

User::create()

✅ 这些才是正经真静态

❌ 和 where /with/order 不是一伙的

 

---

三、重点:哪些是「假静态」(最容易混淆)

下面这些全部不是静态,是伪装的:

Item::where()

Item::with()

Item::join()

Item::field()

Item::order()

Item::limit()

Item::group()

Item::select()

Item::find()

Item::save() // 不行,save是实例方法

记忆口诀:

所有「链式拼接」的,全是假静态

where、with、join、field、order 全部算。

 

---

四、用一行代码看透区别

真静态(Db / Model 静态方法)

// 天生就是给 :: 写的

Db::name('item');

User::get(1);

假静态(TP 语法糖)

// 看着是 ::,底层自动 new

Item::where('id',1)->select();

 

// 等价原生写法

(new Item())->where('id',1)->select();

 

---

五、最简单好记 终极口诀

1. Db:: 全部是真静态

2. 模型::get /all/create /instance 是真静态

3. 模型::where/with/order/select 全是假静态

4. 你自己写的方法:

  - 加 static ➜ 真静态 ::

  - 不加 static ➜ 普通对象 ->

 

---

六、给你解决你刚才的疑问

是不是不加 with 直接 where 就跑不了?

❌ 完全错

// 完全合法、纯单表、正常运行

Item::where('status',1)->select();

with 只是一个普通链式方法,可有可无,不影响任何东西

 

---

现在:

真静态、假静态、Db 双冒号、模型双冒号

彻底分得明明白白了吧 😎

更多推荐