Calling non-static methods statically

1 month ago

SammyAbukmeil

Code

class a {
    function nonStaticMethod() {
        echo sprintf(
            "nonStaticMethod, \$this = %s\n",
            isset($this) ? get_class($this) : 'unset'
        );
    }

    static function staticMethod() {
        echo sprintf(
            "staticMethod, \$this = %s\n",
            isset($this) ? get_class($this) : 'unset'
        );
    }
}

class b {
    function callA() {
        a::staticMethod();
        a::nonStaticMethod();

        $a = new a();
        $a->staticMethod();
        $a->nonStaticMethod();
    }
}

$b = new b();
$b->callA();

Output

staticMethod, $this = unset
PHP Deprecated:  Non-static method a::nonStaticMethod() should not be called statically in phar:///Applications/Tinkerwell.app/Contents/Resources/tinkerwell/tinker.phar/index.php(108) : eval()'d code on line 17
New course: Desktop apps with Electron