访问方法的方法不同

Som*_*omk 2 php oop scope-resolution

我已经看到有两种不同的方法来访问类中的方法.行为是否有任何差异,或者它们是同一行为的纯粹替代语法?

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

A::foo();
Run Code Online (Sandbox Code Playgroud)

Col*_*son 6

你不能只使用其中一个.::用于静态方法和变量,而是->用于方法和变量.这是来自C++语法的"灵感".

class A {
    public function __construct() {}
    public function foo() {}
}
$a = new A();
$a->foo();
// Or use the shorter "new A()->foo()";
//   It won't return typeof(A), it will return what foo() returns.
// The object will still be created, but the GC should delete the object
Run Code Online (Sandbox Code Playgroud)

要么

class A {
    public static function foo() {}
}
A::foo();
Run Code Online (Sandbox Code Playgroud)

根据DCoder,::可以用于调用父方法,但我不确定这一点.

class B {
    public function __construct() {}
    public function foo() {}
}
class A extends B {
    public function __construct() {
        // Code
        parent::__construct()
    }
    public function foo() {
        // Code
        parent::foo()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 还有一个有用的用于`::` - 从子类(`parent :: method()`)中相同方法的重载版本中调用父类的方法. (2认同)