If we declare a function inside a class as final, we cannot use that function name in its derived classes. That is final keyword avoid method overriding. You can see more about method overriding here.
Example 1:
<?php
class A
{
final function test() // Declare function as final.
{
echo 'From base class';
}
}
class B extends A
{
function test() // Will throw an error.
{
echo 'This never run.';
}
}
?>
And we can also avoid extending a class by declaring a class as final.
Example 2:
final class A // Declare class as final.
{
function fun()
{
}
}
class B extends A // Will throw an error.
{
}
And note we can only declare function and class as final, cannot declare variable as final.
Example 1:
<?php
class A
{
final function test() // Declare function as final.
{
echo 'From base class';
}
}
class B extends A
{
function test() // Will throw an error.
{
echo 'This never run.';
}
}
?>
And we can also avoid extending a class by declaring a class as final.
Example 2:
final class A // Declare class as final.
{
function fun()
{
}
}
class B extends A // Will throw an error.
{
}
And note we can only declare function and class as final, cannot declare variable as final.
No comments:
Post a Comment