EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Access Modifiers in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Access Modifiers in PHP

Access Modifiers in PHP

Introduction to Access Modifiers in PHP

Access modifier is a way through which we can set accessibility scope and rights to the variable of any other identifiers in PHP. PHP supports various keywords to make any variable to access any variable and the identifiers. We can assign these keywords to the class, function or identifiers. These keywords – public, private, protected, abstract, final, etc.

When to use Access Modifiers in PHP?

PHP has some limitations on its access modifier, unlike Java. We cannot use all the PHP access modifier on the class level, function level, and the identifier level. We can use these access modifiers as per our business need to grant permission or revoke permission throughout the program or the application.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Here are the list modifiers and whether it is applicable or not:

Access Modifier Class Level Function Level Variable Level
public NA YES YES
private NA YES YES
protected NA YES YES
abstract YES YES NA
final YES YES NA
Static NA YES YES

In the above tale, NA denotes the Not Applicable. That means we cannot use the public, private and protected on the class level. We can use the abstract and the final only on the class level.

Various Access Modifiers in PHP

Here are the following Access Modifiers in PHP mention below

1. Public access modifier

The public is the default modifier like JAVA in PHP. That means if we do not use any modifier with the functions of the identifiers by default it is considered as a public access modifier. This is one of the most widely used. As the moment we come to the re-usability of the code of the function, we usually go with the public access modifier. Because, the public can be used from anywhere, within the class for sure, outside of the class, in the extended class, and if that public re-usable is not bounded to any class, we can use that anywhere we include the file. As mentioned in the above table we cannot use this public modifier with the class along with private and protected as well.

Now, it’s time to see the example of the public access modifier:

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,694 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

<?php
class MyAccess {
var $var = "This is first var";
// print var variable value
function returnVar() {
echo $this->var;
}
}
$obj1 = new MyAccess();$obj1->returnVar();
?>

In the above code, returnVar() function has been defined with no access modifier with it, so this will be working as public as this is the default modifier in the PHP language.

access modifiers in php

public, private and protected will not be applicable at the class level, let’s see it with an example.

<?php
class public MyAccess {
var $var = "This is first var";
function returnVar() {
echo $this->var;
}
}
$obj1 = new MyAccess();
$obj1->returnVar();
?>

The above code will give an error as mentioned below:

( ! ) Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting identifier (T_STRING) in E:\wamp\www\twit\index.php on line 2

This remains the same for private and protected as well.

<?php
class private  MyAccess {
var $var = "This is first var";
}
?>
<?php
class protected  MyAccess {
var $var = "This is first var";
}
?>

2. Private access modifier

This modifier us the private keyword to process with it.  We cannot use the private modifier with the class. We can use this with the class variables and class methods only (as we have mentioned in the above table). When we declare and use the private then it cannot be accessed using the object of the class. It can only be used within the class.

For Example

<?php
class MyAccess {
var $var = "This is first var";
private $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
$obj1 = new MyAccess();
echo $obj1->fist_name; // will give the error
$obj1->set_fist_name("Jai Shre");
$obj1->returnVar();
?>
echo $obj1->fist_name; // will give the error

This line of code we can use as this will come up with the error. This is something we cannot access the private variable using the object of that class. But we can use this by using its setting and the getter method as we are using in the above code.  $obj1->set_fist_name(“Jai Shre”); line of code will set the value in the variable and using $obj1->returnVar(); we can get the value of the set variable.

3. Protected access modifier

Just like public and private, protected itself doesn’t support at the class level. Like a private modifier, protected also restricts the access of the class variables or the function from outside of the class.  It can be used within the same class and from the subclass (child class).

For Example 

<?php
class MyAccess {
var $var = "This is first var";
protected $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class child extends MyAccess {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo $this->fist_name;
}
}
$obj1 = new child();
//echo $obj1->fist_name; // will give the error
$obj1->setVal("Jai Shre");
$obj1->getVal();
?>

echo $obj1->fist_name; the line of code will give the below error

Output:

Fatal error: Cannot access protected property MyAccess::$fist_name in E:\wamp\www\twit\index.php on line 20

4. Abstract access modifier

It can be used on the class and the function, not on the class variable. If any class has at least one abstract function then it must be declared as an abstract. We cannot instantiate the abstract class. An abstract class is mainly considered as an incomplete class.

5. Final access modifier

If any class is declared as a final, we cannot extend that class. PHP restricts the final class from being inherited.

6. Static access modifier

The static keyword can be used to make any function as static. It enables the ability of that function so that one can use within creating an object of that class in which it has been declared. Static method example –

public static function static Function()
{
// declaration goes here..
}

Conclusion

We should always use the access modifier as per the business requirements. Using private and protected, we can restrict the direct use of private variables and private methods from outside of the declared class.

Recommended Articles

This is a guide to Access Modifiers in PHP. Here we discuss the Various Access Modifiers in PHP with the examples and outputs. You may also look at the following article to learn more –

  1. Abstract Class in PHP
  2. Patterns in PHP
  3. PHP Switch Statement
  4. Variables in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More