Access Specifiers in PHP

Advertisements

Class and Object in PHP Abstraction in PHP

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

?>

Class and Object in PHP Abstraction in PHP

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements