php 什么是新静态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15898843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:09:48  来源:igfitidea点击:

what means new static?

php

提问by Hello

I saw in some frameworks this line of code:

我在一些框架中看到了这行代码:

return new static($view, $data);

how do you understand the new static?

你是怎么理解的new static

回答by Lightness Races in Orbit

When you write new self()inside a class's member function, you get an instance of that class. That's the magic of the selfkeyword.

当您new self()在类的成员函数中编写代码时,您将获得该类的一个实例。这就是self关键字的神奇之处

So:

所以:

class Foo
{
   public static function baz() {
      return new self();
   }
}

$x = Foo::baz();  // $x is now a `Foo`

You get a Fooeven if the static qualifier you used was for a derived class:

Foo即使您使用的静态限定符用于派生类,您也会得到一个:

class Bar extends Foo
{
}

$z = Bar::baz();  // $z is now a `Foo`

If you want to enable polymorphism (in a sense), and have PHP take notice of the qualifier you used, you can swap the selfkeyword for the statickeyword:

如果您想启用多态(在某种意义上),并让 PHP 注意到您使用的限定符,您可以将self关键字替换为static关键字:

class Foo
{
   public static function baz() {
      return new static();
   }
}

class Bar extends Foo
{
}

$wow = Bar::baz();  // $wow is now a `Bar`, even though `baz()` is in base `Foo`

This is made possible by the PHP feature known as late static binding; don't confuse it for other, more conventional uses of the keyword static.

这可以通过称为后期静态绑定的 PHP 特性实现;不要将它与关键字 的其他更传统的用法混淆static