Home  >  Article  >  Backend Development  >  Why Do Calls to Non-Static Methods Using PHP\'s Double Colon Syntax Fail?

Why Do Calls to Non-Static Methods Using PHP\'s Double Colon Syntax Fail?

Linda Hamilton
Linda HamiltonOriginal
2024-11-21 09:53:10391browse

Why Do Calls to Non-Static Methods Using PHP's Double Colon Syntax Fail?

Calling Non-Static Methods Using Double Colon Syntax

In PHP, it's possible to call non-static methods using the syntax of static methods, class::method. However, why is it that such calls fail?

Consider the following example:

class Teste {
    public function fun1() {
        echo 'fun1';
    }
    public static function fun2() {
        echo "static fun2";
    }
}

Calling Teste::fun2() works because it's a static method, but calling Teste::fun1() raises an error.

The explanation lies in PHP's loose handling of static vs. non-static methods. When a non-static method is called statically from within a non-static method of class C, $this inside the non-static method ns refers to the instance of C.

For example:

class A {
    public function test() {
        echo $this->name;
    }
}

class C {
    public function q() {
        $this->name = 'hello';
        A::test();
    }
}

$c = new C;
$c->q(); // prints hello

Although this may cause unexpected behavior, it's not an error unless strict error reporting is enabled. Therefore, calling non-static methods statically using double colon syntax is discouraged, as it can lead to errors or confusing behavior.

The above is the detailed content of Why Do Calls to Non-Static Methods Using PHP\'s Double Colon Syntax Fail?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn