0

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";
halfer
  • 19,824
  • 17
  • 99
  • 186
shaon
  • 17
  • 6

1 Answers1

2

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)

Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
  • weirdly, i can comment here but not to the post i gave link to. I understand the concept of static but my confusion is with the 2 lines of code I mentioned in my question. – shaon Mar 14 '20 at 14:55
  • `public function __call($name, $arguments) {}` is the **magic** of the second line. This is a [magic function](https://www.php.net/manual/en/language.oop5.overloading.php#object.call) will be called, when a method of an instance is called **which is not existing**. Name is the name of the method. You can use this trick for magic getters (__get) and setters (__set), but I do not recommend using that. – Markus Zeller Mar 14 '20 at 15:07
  • 1
    thanks. I think i understand now. I am accepting your answer but can you please also add your comments with your answer? – shaon Mar 14 '20 at 15:27