使用通用逻辑扩展接口

Extend interface with common logic

假设我有,

interface Foo {

}

class FooClass implements Foo {

}

有没有办法在 FooClass 之外的界面中添加一些逻辑,以便我可以这样做:

$foo = new FooClass();
$foo->Bar();

其中 Bar 是适用于所有 Foo 的方法?我要求的是类似于 extension methods in C# 的东西,但在我的情况下,我只想扩展接口。

我知道我可以添加一个自定义静态函数 Bar,它接受 Foo 作为参数,但我想知道 PHP 中是否有任何东西给我 $foo->Bar() 糖.

编辑: 我想我不够清楚。我有几个来自外部库的类似接口(还有许多 类 实现它们)。将它们更改为抽象 类 对我来说不是一个选项。

我认为最接近 PHP 的是所谓的 traits

<?php
interface Foo {

}

trait myTraits {
        function bar() { echo "BarMethod"; }
}

class FooClass implements Foo {
        use myTraits;
}

$foo = new FooClass();
$foo->Bar();
?>

这将输出 "BarMethod".