Home > Backend Development > PHP Tutorial > Late binding in PHP

Late binding in PHP

WBOY
Release: 2016-07-29 09:10:45
Original
1231 people have browsed it

Look at an example first:

<code><?php
    class A {
        public static function who() {
            echo __CLASS__;
        }
        public static function test() {
            self::who();
        }
    }
    
    class B extends A {
        public static function who() {
            echo __CLASS__;
        }
    }
    
    B::test();
?></code>
Copy after login

Output:

<code>A
</code>
Copy after login

If using late binding:

<code><?php
    class A {
        public static function who() {
            echo __CLASS__;
        }
        public static function test() {
            static::who(); // 后期静态绑定从这里开始
        }
    }
    
    class B extends A {
        public static function who() {
            echo __CLASS__;
        }
    }
    
    B::test();
?></code>
Copy after login

Output:

<code>B
</code>
Copy after login

Use self:: or CLASS to make a static reference to the current class, depending on the class in which the current method is defined , rather than the class of the caller.

"Late binding" means that static:: is no longer resolved to the class in which the current method is defined, but is calculated at actual runtime. It can also be called "static binding" because it can be used for (but is not limited to) calls to static methods.

The above has introduced late binding in PHP, including static methods. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
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