Wednesday, 5 May 2021

PHP OOP -> protected method can only be called in child class only, not an instance of child

 <?php

// The following will result error, as protected method parentTesterFunction () is called on instance of child.

class ParentTester {

    

    protected function parentTesterFunction () {

        echo "parent function";

    }

    

}


class ChildTester extends ParentTester {

   

}


$childTester = new ChildTester();

$childTester->parentTesterFunction();


--------------Result --------

<br />

<b>Fatal error</b>:  Uncaught Error: Call to protected method ParentTester::parentTesterFunction() from context '' in [...][...]:19

Stack trace:

#0 {main}

  thrown in <b>[...][...]</b> on line <b>19</b><br />



--------------------------------------------------------------------------------------------------
Following will work 

<?php

class ParentTester {
    
    protected function parentTesterFunction () {
        echo "parent function";
    }
    
}


class ChildTester extends ParentTester {
    
    public function parentTesterFunction() {
        return parent::parentTesterFunction();
    }
    
}

$childTester = new ChildTester();
$childTester->parentTesterFunction();

--------------Result --------
parent function

No comments:

Post a Comment