美文网首页
"final" keyword is useless in t

"final" keyword is useless in t

作者: 张霸天 | 来源:发表于2017-03-24 17:58 被阅读0次

Keep in mind; "final"keyword is useless in traits when directly using them, unlike extending classes / abstract classes.


<?php
trait Foo {
    final public function hello($s) { print "$s, hello!"; }
}
class Bar {
    use Foo;
    // Overwrite, no error
    final public function hello($s) { print "hello, $s!"; }
}

abstract class Foo {
    final public function hello($s) { print "$s, hello!"; }
}
class Bar extends Foo {
    // Fatal error: Cannot override final method Foo::hello() in ..
    final public function hello($s) { print "hello, $s!"; }
}
?>

But this way will finalize trait methods as expected;

<?php
trait FooTrait {
    final public function hello($s) { print "$s, hello!"; }
}
abstract class Foo {
    use FooTrait;
}
class Bar extends Foo {
    // Fatal error: Cannot override final method Foo::hello() in ..
    final public function hello($s) { print "hello, $s!"; }
}
?>

相关文章

网友评论

      本文标题: "final" keyword is useless in t

      本文链接:https://www.haomeiwen.com/subject/grnfottx.html