PHP Syntax OOP Classes Components Methods Custom Scope Protected

 

- Info:

- Method is declared as protected by using keyword protected.

- Protected methods can be accessed only from within the class in which they are defined and its subclases.

This is in contrast to private methods which can't be accessed from subclasess (classes that extend this class).

 

- Example:

- This example shows how to access provate method from another method of the same class.

- Creat PHP Console Application Test.php.

 

Test.php

<?php

//CLASS PERSON.-------------------------------------------------------

class Person {

protected function getName() { return "John"; }

}

//CLASS SOLDIER.------------------------------------------------------

class Soldier extends Person {

public function displayName() { echo $this->getName(); }

}

//USE CLASS.----------------------------------------------------------

$john = new Soldier(); //Create Object from Class.

$john->displayName(); //Call protected method from superclass.

?>