gpt4 book ai didi

php - "Class X extends Y (abstract), Y implements Z (interface). "无法调用接口(interface) Z 的抽象方法”

转载 作者:可可西里 更新时间:2023-11-01 00:19:34 25 4
gpt4 key购买 nike

这是我的 PHP 抽象类。最底层的类是将扩展抽象类并将一些复杂的计算逻辑留给父实现的类之一。

接口(interface)类(最顶层的抽象)的要点是强制那些较低的实现有自己的static public function id($params=false){ 方法。

// My top level abstraction, to be implemented only by "MyAbstraction"
interface MyInterface{
static public function id();
}

// My second (lower) level of abstraction, to be extended
// by all child classes. This is an abstraction of just the
// common heavy lifting logic, common methods and properties.
// This class is never instantiated, hence the "abstract" modifier.
// Also, this class doesn't override the id() method. It is left
// for the descendant classes to do.

abstract class MyAbstraction implements MyInterface{

// Some heavy lifting here, including common methods, properties, etc
// ....
// ....

static public function run(){
$this->id = self::id(); // This is failing with fatal error
}
}

// This is one of many "children" that only extend the needed methods/properties
class MyImplementation extends MyAbstraction{

// As you can see, I have implemented the "forced"
// method, coming from the top most interface abstraction
static public function id(){
return 'XXX';
}
}

最终结果是,如果我调用:

$o = new MyImplementation();
$o->run();

我得到一个 fatal error : fatal error :无法调用抽象方法 MyInterface::id();

为什么 MyAbstraction::run() 调用其父类(接口(interface))的 id() 方法而不是其子(后代)类中的方法?

最佳答案

  1. 在接口(interface)中声明的所有方法都必须是公共(public)的;这是接口(interface)的本质。 Reference - PHP interface

  2. 您正在 MyAbstraction 类中使用 self::id()self 始终引用同一个类。 reference self vs static

你应该使用 static 而不是 self。引用下面的代码。

interface MyInterface{
public function id();
}

abstract class MyAbstraction implements MyInterface{

public $id;
// Some heavy lifting here, including common methods, properties, etc
// ....
// ....

public function run(){
$this->id = static::id(); // This is failing with fatal error
}
}

class MyImplementation extends MyAbstraction{

// As you can see, I have implemented the "forced"
// method, coming from the top most interface abstraction
public function id(){
return 'XXX';
}
}

$o = new MyImplementation();
$o->run();

在上面的代码中,static::id() 将调用上下文中类的函数,即 MyImplementation 类。

这种现象称为Late Static Binding

关于php - "Class X extends Y (abstract), Y implements Z (interface). "无法调用接口(interface) Z 的抽象方法”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com