search

Home  >  Q&A  >  body text

Static properties can be called in non-static methods

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_LikeGod_Like2040 days ago2179

reply all(3)I'll reply

  • God_Like

    God_Like2019-04-15 17:18:21

    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

    reply
    0
  • 天蓬老师

    天蓬老师2019-04-14 22:23:30

    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"


    reply
    1
  • Cancelreply