Heim  >  Artikel  >  Backend-Entwicklung  >  PHP 中的新语法 new static 是个啥意思?

PHP 中的新语法 new static 是个啥意思?

WBOY
WBOYOriginal
2016-06-06 20:39:26887Durchsuche

<code>php</code><code><br> public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }
</code>

这个new static($user);是个啥意思呀??

回复内容:

<code>php</code><code><br> public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }
</code>

这个new static($user);是个啥意思呀??

简单通俗的来说, self就是写在哪个类里面, 实际调用的就是这个类.所谓的后期静态绑定, static代表使用的这个类, 就是你在父类里写的static, 然后通过子类直接/间接用到了这个static, 这个static指的就是这个子类, 所以说static和$this很像, 但是static可以用于静态方法和属性等.

举个简单的例子,

<code>class ATest {

    public function say()
    {
        echo 'Segmentfault';
    }

    public function callSelf()
    {
        self::say();
    }

    public function callStatic()
    {
        static::say();
    }
}

class BTest extends ATest {
    public function say()
    {
        echo 'PHP';
    }
}

$b = new BTest();
$b->say(); // output: php
$b->callSelf(); // output: segmentfault
$b->callStatic(); // output: php
</code>

就是这个样纸~

类似于self但是static关键字可以用于后期静态绑定。参考:http://php.net/manual/zh/language.oop5.late-static-bindings.php

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn