Increasing method visibility through extension

Although it’s nothing superspecial, I wanted to illustrate how it is possible to modify the visibility of a parent class method when extending it, to convert it from ‘protected’ to ‘public’. Assume we have a base class which exposes a protected function called ‘Test’. We want to extend the class and make that function public in our extension. Here’s how:

<?php
    class Fred {
        protected function Test() {
            ?>Boo!<?php
        }
    }
 
    class Barney extends Fred {
        public function Test() {
            parent::Test();
        }
    }
 
    $barney = New Barney();
    $barney->Test();
?>

Notice that $barney->Test() is a public method call. It’s also possible to disallow this kind of behavior from the parent’s perspective by declaring a method as final. This way it can no longer be overridden (including its visibility):

<?php
    class Fred {
        final protected function Test() {
            ?>Boo!<?php
        }
    }
?>

Leave a Reply