PHP Access Modifier - php certification - Phptpoint.com

PHP Access Modifier

/ins>

Public Private Protected in PHP

Access Modifier allows you to alter the visibility of any class member(properties and method).

In php 5 there are three scopes for class members.

  • Public
  • Protected and
  • Private

Public Access modifier

Public access modifier is open to use and access inside the class definition as well as outside the class definition.

Output
ravish
ravish
ravish

In the above example
Create a demo class with a public property $name and method disp( ).
create a child class of demo class(using inheritance) with a method show( ).
inside show( ) method of child class call the global property of parent class(demo).
Now create the object of child class, call its own method show(), its parent class method disp( ) and parent class property $name.

Protected access modifier

Protected is only accessible within the class in which it is defined and its parent or inherited classes.

Output
1000
0

Private access modifier

Private is only accessible within the class that defines it.( it can’t be access outside the class means in inherited class).

Output
Fatal error: Call to private method demo::show()

use of all access modifier in a single example

Create a parent class with public, private and protected properties and try to access these properties with their child class.

Eg(summary)

Output
Welcome : shashi
Profile : developer
Salary :