How to understand self in PHP?

    class A {
        const STR = "A";

        public function x() {
            echo self::STR;
        }
    }

    class B extends A{
        const STR = "B";
    }

    (new B)->x();

the final output is A. how do you understand this?

guess 1:
self will be bound to the current class at compile time, which can be understood as replacing all self with the class name at compile time.
so that after other classes inherit the parent class method, the method code is not self::xxx, but the parent class name:: xxx
, so the str in the example is the str in the parent class

.

conjecture 2:
the subclass inherits the parent method, in fact, it does not take the parent method, but has access to the parent method.
when calling a method that is not in the subclass, it will look for it in the parent class, and execute it in the parent class. Naturally, self points to the parent class

.

which of these two is right?

how do you understand self if it"s all wrong? First of all, thank you for your advice

Mar.28,2021

in fact, their principle is:
self is for the use of the current class.
this is a call to the current class. If the current class does not have one, find the parent class to


.
A static reference to the current class using self:: or CLASS , depending on the class in which the current method is defined

your second guess is right.

PHP static binding


<?php
class A {
    const STR = "A";

    public function x() {
        echo self::STR;
    }
}

class B extends A{
    const STR = "B";  
    public function x() {
        echo self::STR;
    }  
}

(new B)->x();

copy it so that you can understand


self: defines the class in which the current method is located
the class in which the static: runtime is located


in short, self points to the current class this points to the current object


self refers to the first use of the parent class attribute
static refers to the first use of the current class attribute

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e4bd99-44e60.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e4bd99-44e60.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?