问题
What i want is the ability to make "final traits" with the behaviour as described below. I realise this is not possible with traits(or is it? that would make me so happy), but I'm just trying to convey what I want to do.
So, i want to have a trait that is
trait Content {
public final function getPostContent(){ /*...*/ }
public final function setPostContent($content){ /*...*/ }
}
What I want is
Marking the functions in the traits as final making sure that if a class uses this trait, the trait implementation is the guaranteed implementation
class MyClass {
use Content;
public function getPostContent() { // This should not be allowed
return null;
}
}
I want to be able to somehow check if a class uses a trait(i.e. $myObject instanceof Content)
class MyClass {}
class MyClassWithContent {
use Content;
}
var_dump((new MyClass) instanceof Content); // "bool(false)"
var_dump((new MyClassWithContent) instanceof Content; // "bool(true)"
Making sure that when the trait is being used, the methods name/visibility can not be changed. So, none of this should be allowed.
class MyDeceptiveClass {
use Content {
Content::getPostContent as nowItsNotCalledGetPostContentAnymore();
Content::setPostContent as protected; // And now setPostContent is protected
}
}
回答1:
Methods in traits are overwritten by methods defined in a class, even if the trait method is final
:
<?php
trait Bar {
final public function fizz() {
echo "buzz\n";
}
}
class Baz {
use Bar;
public function fizz() {
echo "bam\n";
}
}
$x = new Baz;
$x->fizz(); // bam
Taking a look at the precedence section in the traits documentation:
An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.
来源:https://stackoverflow.com/questions/33480919/use-final-on-traits-in-php