Understanding an article regarding scope resolution in PHP-ThrowExceptions

Exception or error:

I was looking for when and how scope resolution :: is used. So I found out that it can be used for calling static variable/function and also for. But there seems to be more to it considering this answer in Stack Overflow.

My confusion is about the last two lines of code from this answer:

/* This is more tricky
 * in the first case, a static call is made because $this is an
 * instance of A, so B::dyn() is a method of an incompatible class
 */
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";

/* in this case, an instance call is made because $this is an
 * instance of B (despite the fact we are in a method of A), so
 * B::dyn() is a method of a compatible class (namely, it's the
 * same class as the object's)
 */
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";
How to solve:

The :: is called in static uses. This is meant for classes with static properties and methods where you call it without an instance.

class A {
    public static function callMethod(): void {}
}

A::callMethod();

will call method callMethod() without having an instance.

class A {
    public function callMethod(): void {}
}

$a = new A();
$a->callMethod();

will call callMethod() from instance $a.

Note, that static methods can only be called without instance.

Additional explanation

From the answer you linked, a method is called dynamically even it was not defined. When you use the magic caller method, this is possible.

class A {
    public function __call($name, $arg) {
        $args = implode(', ', $arg ?? []);
        echo "You called {$name} with ({$args})\n";
    }
}

So now you can call any method without an exception.

$a = new A();
$a->hello('world');

You called hello with (world)

Leave a Reply

Your email address will not be published. Required fields are marked *