search

Home  >  Q&A  >  body text

Why can PHP directly call non-static methods of a class through ::?

code show as below:

<?php

class Demo
{
    public function testing()
    {
        echo "testing\n";
    }
}

Demo::testing();

php7.0 execution output:

$ php demo.php 
testing

php5.6 execution output

$ php demo.php
PHP Strict Standards:  Non-static method Demo::testing() should not be called statically in /home/runner/Code/funny/demo.php on line 11

testing

Is there such an operation?? What is the principle??

滿天的星座滿天的星座2731 days ago549

reply all(7)I'll reply

  • 大家讲道理

    大家讲道理2017-06-10 09:49:28

    http://www.laruence.com/2012/...

    Hahaha, thank you all for your answers. For the specific reasons, please read Brother Bird’s article above

    reply
    0
  • 高洛峰

    高洛峰2017-06-10 09:49:28

    If a class below version 5.6 directly calls methods and attributes without instantiation, the methods and attributes must be static methods, that is, if the Demo class directly calls the testing method, the test must be public static function testing() { }. Otherwise, an error will be reported.
    I don’t know if there is no need to declare anything above 7.0

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-10 09:49:28

    I saw it, but php-cli can execute it, but php-fpm still can’t

    Deprecated: Non-static method Demo::testing() should not be called statically in test.php on line 11
    
    testing

    reply
    0
  • 某草草

    某草草2017-06-10 09:49:28

    Although this can be used, it is not recommended.

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-10 09:49:28

    php7.0 can be written like this, but php5.6 definitely cannot. It can also be written as self::testing

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-10 09:49:28

    __callStatic()

    reply
    0
  • 学习ing

    学习ing2017-06-10 09:49:28

    It can be considered that the implementation of PHP is not rigorous.

    If $this is not used in the non-static method, you can use:: to call it.

    reply
    0
  • Cancelreply