Access Specifiers in PHP


Prev Tutorial Next Tutorial

Access Specifiers in PHP

There are three types of Access Specifiers available in PHP, Private, Protected and Public.

Public: Class members declared public can be accessed everywhere.

Protected: Class members declared protected can be accessed only within the class itself and by inheriting classes.

Private: Class members declared as private may only be accessed by the class that defines the member.

access specifiers in php

Syntax

<?php

class MyClass
{
  public $public = 'Public';
  protected $protected = 'Protected';
  private $private = 'Private';

 function printHello()
  {
   echo $this->public;
   echo $this->protected;
   echo $this->private;
  }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected properties, but not private
    public $public = 'Public2';
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public2, Protected2, Undefined

?>

Prev Tutorial Next Tutorial

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain, Tutorialday.com, SeosmoTools.com @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: hitesh.xc@gmail.com WhatsApp no. 8882538826

Yahoo Advertisements