企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# new self()和new static()的区别 1. new self()和new static()的区别只有在继承中才能体现出来,如果没有任何继承,那么这两者是没有区别的。 2. 在继承中,new self()返回的实例是万年不变的,无论谁去调用,都返回同一个类的实例,而new static()则是由调用者决定的。 实例1:无继承 ~~~ class Father { public function useSelf() { return new self(); } public function useStatic() { return new static(); } } $f = new Father(); echo get_class($f->useSelf())."\n";// 输出 Father echo get_class($f->useStatic())."\n";// 输出 Father ~~~ 输出结果: Father Father 实例2:继承(Father类为实例1的Father类) ~~~ class Sun1 extends Father { } class Sun2 extends Father { } $sun1 = new Sun1(); $sun2 = new Sun2(); echo get_class($sun1->useSelf())."\n"; // 输出 Father echo get_class($sun1->useStatic())."\n"; // 输出 Sun1 echo get_class($sun2->useSelf())."\n"; // 输出 Father echo get_class($sun2->useStatic())."\n"; // 输出 Sun2 ~~~ 输出结果: Father Sun1 Father Sun2 资料来源: http://www.cnblogs.com/shizqiang/p/6277091.html