如果在使用的过程中没有继承的话,两者是没有区别的,都是返回当前方法所在类的实例 //democlassbaba{functiontest1(){returnnewself();//返回类baba的实例}functiontest1(){returnnewstatic();//返回类baba的实例}} 有继承的情况下,self()返回父类的实例,static()返回继承父类的子类的实例。 //democlassbabaex...
publicstaticfunction get_static() { returnnewstatic(); } } classB extends A {} echo get_class(B::get_self());// A echo get_class(B::get_static());// B echo get_class(A::get_static());// A 于是上网查了下,他们两个的区别。 self - 就是这个类,是代码段里面的这个类。 static...
1.self返回的是 new self 中关键字 new 所在的类中,比如这里例子的 : 1 2 3 publicstaticfunctiongetSelf() { returnnewself();// new 关键字在 Father 这里 } 始终返回 Father。 new static 2.static 则上面的基础上,更聪明一点点:static 会返回执行 new static() 的类,比如 Son 执行 get_class(Son...
方法 create2 中使用了 return new static(),毫无疑问,调用该方法的是对象 $b,那么返回的也肯定是 class B 本身。方法 create1 中使用 get_class($this) 通过对象本身 $this,获取类名。因为 $this 指向 class B,所以返回的是 B,而 return new $class() 等同于 return new B(),也就是类B本身。...
因为this指向classB,所以返回的是B,而returnnewclass() 等同于 return new B(),也就是类B本身。 再进一步 既然我们区分了 self 可以不经类实例化就可以使用其方法,static 必然是实例化后对象的引用,那么看下面这个例子,就会很清楚了: 代码语言:javascript 复制 classFoo{public$name=static::class;}$Foo=newFo...
php public static function findIdentityByAccessToken($token, $type = null) { foreach (self::$users as $user) { if ($user['accessToken'] === $token) { return new static($user); } } return null; } 这个new static($user);是个啥意思呀??php...
方法create2 中使用了 return new static(),毫无疑问,调用该方法的是对象 $b,那么返回的也肯定是 class B 本身。 方法create1 中使用 get_class($this) 通过对象本身 $this,获取类名。因为 $this 指向 class B,所以返回的是 B,而 return new $class() 等同于 return new B(),也就是类B本身。
new static()是php5.3以后引入新的特性,延迟静态绑定.访问的是当前实例化的那个类,那么 static 代表的就是那个类。 new self() 是指的不是调用上下文,它指的是解析上下文. class Test { public static funtion getSelf(){ return new self(); }
new self 1.`sel`f 返回的是 `new self` 中关键字 `new` 所在的类中,比如这里例子的 : publicstaticfunctiongetSelf(){returnnewself();// new 关键字在 Father 这里} 始终返回 `Father`。 new static 2.`static` 则上面的基础上,更聪明一点点:`static` 会返回执行 `new static()` 的类,比如 ` ...
虽然现在的PHP 已经可以返回self,但是直到 PHP 8 中static才是有效的返回类型。考虑到 PHP 动态类型的性质,这个特性对许多开发人员都非常有用。 代码语言:javascript 复制 classFoo{publicfunctiontest():static{returnnewstatic();}} 新的mixed 类型 有些人可能称其为必要之恶:mixed类型会让很多人感到困惑。不过,...