Php class key difference between static and self, the delay static binding

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/mrtwenty/article/details/102692155

static and internal self can class itself as a representative of the class can, for example:

<?php
class Father
{
    public static function init()
    {
        return new self();
    }

    public static function init2()
    {
        return new static();
    }

    public function run()
    {
        return "father\n";
    }
}

echo Father::init()->run();
echo Father::init()->run();

The role of two key above is no different, can instantiate the class, there are differences that subclasses:

<?php

//延迟静态绑定

class Father
{
    public static function init()
    {
        return new self();
    }

    public static function init2()
    {
        return new static();
    }

    public function run()
    {
        return "father";
    }
}

class Son extends Father
{
    public function run()
    {
        return "son";
    }
}

//返回父类的实例,调用的是父类的run 方法
echo Son::init()->run();
//返回子类的实例,调用的是子类的run 方法
echo Son::init2()->run();

When using the self, the class is instantiated class itself, since the init method Father, the Father is so, the use of this static instance of delay, will wait until the calculated actual operation.

 

 

Guess you like

Origin blog.csdn.net/mrtwenty/article/details/102692155