new static

今天研究了一下thinkphp orm的底层,想找找哪里去设定要操作的数据表,结果发现里面有一个new static的东西。

它还有个兄弟,new self,那么它们究竟是干什么用的呢,举个?
class A { public static function get_self() { return new self(); } public static function get_static() { return new static(); } } class B extends A {} echo get_class(B::get_self()); // A echo get_class(B::get_static()); // B echo get_class(A::get_static()); // A

new self 获取的是当前代码段的这个类。这个在class A 中写的方法,就算你在class B 中继承了,调用时返回的还是 class A 中的代码。
new static 是PHP 5.3新增的方法,有点$this的味道,调用对应的 class 就返回 对应 class 的方法。

具体参考:
http://php.net/manual/zh/language.oop5.late-static-bindings.php

发布了9 篇原创文章 · 获赞 3 · 访问量 1319

猜你喜欢

转载自blog.csdn.net/qq_34051908/article/details/90799977
new
今日推荐