PHP 5 新增了一个 final 关键字。如果父类中的方法被声明为final,则子类无法覆盖该方法; 如果一个类被声明为
final,则不能被继承。
Example #1 Final 方法示例
代码如下
复制代码
代码如下
复制代码
class BaseClass { public function test() { echo "BaseClass::test() called\n"; }
final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; } }
class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() called\n"; } } // 产生 Fatal error: Cannot override final method BaseClass::moreTesting() ?> Example #2 Final 类示例
final class BaseClass { public function test() { echo "BaseClass::test() called\n"; }
// 这里无论你是否将方法声明为final,都没有关系 final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; } }
class ChildClass extends BaseClass { } // 产生 Fatal error: Class ChildClass may not inherit from final class (BaseClass) ?>
class BaseClass { public function test() { echo "BaseClass::test() called\n"; }
final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; }}class ChildClass extends BaseClass {
public function moreTesting() { echo "ChildClass::moreTesting() called\n";
}
}
// 产生 Fatal error: Cannot override final method BaseClass::moreTesting()
final class BaseClass {<🎜> public function test() {<🎜> echo "BaseClass::test() called\n";<🎜> }<🎜> <🎜> // 这里无论你是否将方法声明为final,都没有关系<🎜> final public function moreTesting() {<🎜> echo "BaseClass::moreTesting() called\n";<🎜> }<🎜>}<🎜><🎜>class ChildClass extends BaseClass {<🎜>}<🎜>// 产生 Fatal error: Class ChildClass may not inherit from final class (BaseClass)<🎜>?>
class SubObject<🎜>{<🎜> static $instances = 0;<🎜> public $instance;<🎜><🎜> public function __construct() {<🎜> $this->instance = self::$instances; } public function __clone() { $this->instance = self::$instances; }}class MyCloneable{ public $object1; public $object2; function __clone() { // 强制复制一份this->object, 否则仍然指向同一个对象 $this->object1 = clone $this->object1; }}$obj = new MyCloneable();$obj->object1 = new SubObject();$obj->object2 = new SubObject();$obj2 = clone $obj;print("Original Object:\n");print_r($obj);print("Cloned Object:\n");print_r($obj2);?>