理解一篇关于PHP范围解析的文章

  • 本文关键字:范围 PHP 文章 一篇 php
  • 更新时间 :
  • 英文 :


我一直在寻找何时以及如何使用范围解析。所以我发现它可以用于调用静态变量/函数,也可以用于。但考虑到Stack Overflow中的这个答案,似乎还有更多的内容。

我的困惑是关于这个答案的最后两行代码:

/* 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";

::在静态使用中被调用。这适用于具有静态属性和方法的类,在这些类中,您在没有实例的情况下调用它。

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

将在没有实例的情况下调用方法CCD_ 2。

class A {
public function callMethod(): void {}
}
$a = new A();
$a->callMethod();

将从实例CCD_ 4调用CCD_。

请注意,静态方法只能调用而不调用实例。

附加说明

根据您链接的答案,一个方法被动态地称为,即使它没有被定义。当您使用magic调用者方法时,这是可能的。

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

因此,现在您可以毫无例外地调用任何方法。

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

你打电话给(世界(你好

最新更新