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

WBOY
Release: 2016-06-06 20:39:26
Original
936 people have browsed it

<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>
Copy after login
Copy after login

这个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>
Copy after login
Copy after login

这个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>
Copy after login

就是这个样纸~

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

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template