Thursday, January 24, 2013

PHP: Public, Protected and Private

These three keywords define the visibility of variables.

  • public: visible for both inside and outside
  • protected: visible only to its own methods
  • private: similar to protected, intended to be accessed only by the class who defines it

An Instance

error_reporting(E_ALL);
class foo{
   public    $a=1;
   protected $b=2;
   private   $c=3;

   function stampa()
   {
      echo $this->b;
      echo $this->c;
   }
}
class bar extends foo{
   function __construct(){
      $this->b = 4;
      $this->c = 5;
   } 
}
$A = new foo;
echo $A->a;
$A->stampa();
$B = new bar;
$B->stampa();

Here is the output,

12343

Notes

  • The version of tested php: 5.3.6-13
  • The instance shows the re-assigning of the private member doesn't make any difference. The inheriting class can not modify private members.
  • The private member is still visible (printed) to the inheriting class.

No comments:

Post a Comment