Static properties can be called in non-static methods
God_Like
God_Like 2019-04-14 19:20:19
0
3
2219

As mentioned at 3:30 in this lesson, static properties cannot be called in non-static methods.

But as a personal test, non-static methods in this class can call static properties

Just use [static property self::property name]

God_Like
God_Like

reply all(2)
God_Like

First of all, thank you very much for the teacher's reply

1. In the sample code you gave, the class does not define the test() method, so the instantiation will run with an error

echo (new Demo )->test(); // "Error"

2. I have been using the php7.2 version to practice things

In the code you gave me, (new Demo)->test() is modified to (new Demo)->test2() and runs

Both output results are peter

Is this proof

The [normal method] of a class can call both the [static property of the class] and the [static method] of the class

Peter-Zhu

First of all, thank you for your serious study attitude. You are right. There are some laxities in the tutorial...

In fact, in ordinary methods, calling static properties directly does not An error will be reported, but static methods must not be called.

In ordinary methods, the official does not recommend the use of static members. The use of static attributes is allowed here. This is a bug left over from history. Maybe it will be in future versions. Correction...

The following is the test code for your reference:

class Demo
{
    // 静态属性
    public static $name = 'peter';
    
    // 静态方法
    public static function hello()
    {
       return self::$name;
    }
    
    //  普通方法1
    public function test1()
    {
        return self::$name;
    }
    
    //  普通方法1
    public function test2()
    {
        return self::hello();
    }
}

echo (new Demo)->test1();    // "peter"
echo '<hr>';
echo (new Demo)->test();    // "Error"


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template