特质;父母& PHP 5.4 中的自我类型提示
虽然这个问题在某种程度上与语言无关(与支持 Traits 的 OOP 语言无关),但我一直在修补 PHP 5.4a 的夜间构建,并遇到了一个奇怪的场景。我似乎无法再运行我的安装,但那是另一个故事了。
给出以下片段:
trait MyTrait
{
public function myMethod(self $object)
{
var_dump($object);
}
}
class MyClass
{
use MyTrait;
}
$myObject = new MyClass();
$myObject->myMethod('foobar'); // <-- here
应该发生什么?我希望出现一个错误,表明 $object
需要是 MyClass
的实例。
当将特征方法复制到 use
-ing 类中时,它们是否逐字复制,以解析此类类继承引用?这是 Trait 的预期功能吗? (我没有使用过支持它们的其他语言)
While this question is somewhat language agnostic (agnostic as far as OOP languages that support Traits) I've been tinkering with the nightly builds of PHP 5.4a, and came across an odd scenario. I can't seem to get my install to run anymore, but that's another story.
Given the following snippet:
trait MyTrait
{
public function myMethod(self $object)
{
var_dump($object);
}
}
class MyClass
{
use MyTrait;
}
$myObject = new MyClass();
$myObject->myMethod('foobar'); // <-- here
What should happen? I would hope for an error, indicating $object
needs to be an instance of MyClass
.
When trait methods are copied into a use
-ing class, are they copied verbatim, as to resolve class inheritance references like these? Is this the intended functionality of a Trait? (I've not worked with another language that supported them)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我已经证实这确实正如我所希望和预期的那样:
所以,这对所有人来说都是好消息。
Well, I've confirmed it is in fact as I had hoped for and expected:
So, good news for all then.
请参阅 RFC 了解更多详细信息:https://wiki.php.net/rfc/horizontalreuse
所以,确实,预期的行为是特征方法的行为与使用它的类中定义的完全一样。
因此,对魔法
__CLASS__
常量的引用也被解析为实际的类名。如果您需要知道特征的名称,您可以使用 __TRAIT__ 来代替。
目标是使小的相关行为可重用,它源于 Smalltalk 世界中 Self 的工作以及后来的 Smalltalk 直接。具有类似结构的其他语言是 Perl6 和 Scala。然而,他们对这个概念有自己的解释,通常具有不同的属性和设计意图。
Please see the RFC for more details: https://wiki.php.net/rfc/horizontalreuse
So, yes indeed, the intended behavior is that the method of the trait behaves exactly as it would have been defined in the class that uses it.
Thus, also references to the magic
__CLASS__
constant are resolved to the actual class name.If you how ever need to know the name of the trait you could use
__TRAIT__
instead.The goal is to make small related behavior reusable and it origins from the work in the Smalltalk world on Self and later Smalltalk directly. Other languages having similar constructs are Perl6 and Scala. However, they have their very own interpretation of the concept with usually different properties and design intents.