Why Can\'t I Call Non-Static Methods Using the Double-Colon Syntax in PHP?

Susan Sarandon
Release: 2024-11-27 01:15:18
Original
898 people have browsed it

Why Can't I Call Non-Static Methods Using the Double-Colon Syntax in PHP?

Calling Non-Static Methods with Double-Colon Syntax

In PHP, static methods can be invoked using the class name followed by the scope resolution operator (::). However, it's generally not possible to call non-static methods in the same manner.

Non-Static Methods with Double-Colon Syntax

The code snippet below attempts to call a non-static method, fun1, using the double-colon syntax:

class Teste {

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

Teste::fun1(); // why?
Teste::fun2(); // ok - is a static method
Copy after login

This code will result in an error, as non-static methods cannot be accessed directly through the class name.

Reason for Restriction

PHP employs loose typing for static vs. non-static methods. When a non-static method is called statically, the $this keyword inside that method will not refer to an instance of the class. This loose behavior can lead to inconsistent and potentially erroneous code.

Static Method Variants

The double-colon syntax is only permissible for calling static methods. Here's an example:

class StaticExample {

    public static function staticMethod() {
        echo "static method";
    }
}

StaticExample::staticMethod(); // valid
Copy after login

Within Non-Static Methods

It's possible to call a non-static method statically from within a non-static method of the same class. In such cases, $this inside the called method will still refer to the correct object instance.

class A {

    public function nonStaticMethod() {
        echo $this->name;
    }
}

class C {

    public function callNonStatic() {
        $this->name = 'Example';
        A::nonStaticMethod(); // valid
    }
}

$c = new C;
$c->callNonStatic(); // prints Example
Copy after login

The above is the detailed content of Why Can\'t I Call Non-Static Methods Using the Double-Colon Syntax in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template