Tuesday, 23 July 2019

Public Members and Protected members in PHP

Public Members
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −
  • From outside the class in which it is declared
  • From within the class in which it is declared
  • From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected.

Private members
By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class. A class member can be made private by using private keyword infront of the member.
Eg:-<?php
class MyClass
{
   private $car = "skoda";
   $driver = "PKS";
   function __construct($par) 
{
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   function myPublicFunction()
 {
      return("I'm visible!");
   }
   private function myPrivateFunction()
 {
      return("I'm  not visible outside!");
   }
}
?>
When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members
A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member. Here is different version of MyClass −
Eg:-<?php
class MyClass {
   protected $car = "skoda";
   $driver = "PKS";
   function __construct($par) 
{
      // Statements here run every time
      // an instance of the class
      // is created.
   }
      function myPublicFunction() 
{
      return("I'm visible!");
   }
      protected function myPrivateFunction()
 {
      return("I'm  visible in child class!");
   }
}

0 comments

Post a Comment