Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
Multiple Inheritance in PHP
Next article icon

PHP Access Modifiers

Last Updated : 12 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In object-oriented programming, access specifiers are also known as access modifiers. These specifiers control how and where the properties or methods of a class can be accessed, either from inside the class, from a subclass, or from outside the class. PHP supports three primary access specifiers:

  • public
  • protected
  • private

1. public

A public properties can be accessed from anywhere, from within the class, by inherited (child) classes, and from outside the class.. If a property is declared public, its value can be read or changed from anywhere in your script.

Now, let us understand with the help of the example:

PHP
<?php class Demo {     public $name = "GeeksforGeeks";      public function showName() {         return $this->name;     } }  $obj = new Demo(); echo $obj->name . "\n";         echo $obj->showName();   ?> 

Output
GeeksforGeeks GeeksforGeeks

2. private

A private property or method is accessible only within the class that declares it. It is not accessible in child classes or from outside the class.

Now, let us understand with the help of the example:

PHP
<?php class MyClass {     private $secret = "Top Secret";      private function getSecret() {         return $this->secret;     }      public function revealSecret() {         return $this->getSecret();  // Allowed internally     } }  $obj = new MyClass(); echo $obj->revealSecret(); // Works echo $obj->secret;      // Error: Cannot access private property echo $obj->getSecret(); // Error: Cannot access private method ?> 

Output
Top Secret Fatal error: Uncaught Error: Cannot access private property MyClass::$secret in /home/guest/sandbox/Solution.php:16 Stack trace: #0 {main}   thrown in /home/guest/sandbox/Solution.php on li...

3. protected

A protected property or method can only be accessed within the class itself and by inheriting classes (subclasses). It is not accessible from outside the class.

Now, let us understand with the help of the example:

PHP
<?php class ParentClass {     protected $message = "Hello from Parent";        protected function showMessage() {         return $this->message;     } }  class ChildClass extends ParentClass {     public function getMessage() {         return $this->showMessage();       } }  $obj = new ChildClass(); echo $obj->getMessage();   echo $obj->message;     ?> 

Output

Hello from Parent Fatal error: Uncaught Error: Cannot access protected property ChildClass::$message in /home/guest/sandbox/Solution.php:18 Stack trace: #0 {main}   thrown in /home/guest/sandbox/Solution.php on line 18

4. Default Access Specifier

In PHP, if no access specifier is provided for a property or method, the default access level is **`public`**. This means the property or method can be accessed from anywhere: within the class, from inherited classes, and from outside the class.

PHP
<?php class Demo {     // No access specifier, defaults to public     $name = "GeeksforGeeks";        // Method with default access specifier (public by default)     function showName() {         return $this->name;     } }  $obj = new Demo(); echo $obj->name . "\n";       // Accessible from outside the class echo $obj->showName();        // Accessible from outside the class ?> 

Output

GeeksforGeeks
GeeksforGeeks

In this example

  • Since no access specifier is defined, both the $name property and the showName() method are public by default.
  • This means they can be accessed from both inside the class and from outside the class, as demonstrated in the example.
Access SpecifierAccess from own classAccessible from derived classAccessible by Object
PrivateYesNoNo
ProtectedYesYesNo
PublicYesYesYes

Default (No Specifier)

Yes

Yes

Yes

Why Use Access Specifiers?

  • Encapsulation: It prevents the object's internal details from being accidentally changed or accessed.
  • Security: Prevents unauthorized access or modification of data.
  • Maintainability: Allows controlled interaction with class members, making code easier to maintain and debug.
  • Inheritance Management: Gives flexibility in what a child class should or shouldn't access.

Best Practices

  • Use private for properties that should never be accessed or modified directly from outside the class.
  • Use protected when you expect subclasses to need access but want to restrict outside interference.
  • Use public only when you intend the member to be accessible and safe to expose.

Conclusion

Access specifiers are foundational in PHP’s OOP model. Proper use of public, protected, and private helps build secure, and well-structured code. Choosing the right access level enforces better design practices and enhances code reusability and maintainability.


Next Article
Multiple Inheritance in PHP

P

parna_28
Improve
Article Tags :
  • Web Technologies
  • PHP
  • PHP Programs
  • PHP-OOP

Similar Reads

    PHP Tutorial
    PHP is a widely used, open-source server-side scripting language primarily designed for web development. It is embedded directly into HTML and generates dynamic content on web pages. It allows developers to handle database interactions, session management, and form handling tasks.PHP code is execute
    9 min read

    Basics

    PHP Syntax
    PHP, a powerful server-side scripting language used in web development. It’s simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with n
    4 min read
    PHP Variables
    A variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script.All variable names start with a dollar sign ($).Variables can store different data types, like integers, strin
    5 min read
    PHP | Functions
    A function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
    8 min read
    PHP Loops
    In PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops. In this article, we will discuss the different types of loops in PHP,
    4 min read

    Array

    PHP Arrays
    Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
    5 min read
    PHP Associative Arrays
    An associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things. For example, the first item is at position 0, the second is 1, and so on. But in an associative array, we use words or names to find things. These
    4 min read
    Multidimensional arrays in PHP
    Multi-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
    5 min read
    Sorting Arrays in PHP
    Sorting arrays is one of the most common operation in programming, and PHP provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys, in ascending or descending order. PHP also allows you to create custom sorting functions.Table of ContentSort Array in
    4 min read

    OOPs & Interfaces

    PHP Classes
    A class defines the structure of an object. It contains properties (variables) and methods (functions). These properties and methods define the behavior and characteristics of an object created from the class.Syntax:<?phpclass Camera { // code goes here...}?>Now, let us understand with the hel
    2 min read
    PHP | Constructors and Destructors
    In PHP, constructors and destructors are special methods that are used in object-oriented programming (OOP). They help initialize objects when they are created and clean up resources when the object is no longer needed. These methods are part of the class lifecycle.In this article, we will discuss w
    5 min read
    PHP Access Modifiers
    In object-oriented programming, access specifiers are also known as access modifiers. These specifiers control how and where the properties or methods of a class can be accessed, either from inside the class, from a subclass, or from outside the class. PHP supports three primary access specifiers: p
    4 min read
    Multiple Inheritance in PHP
    Multiple Inheritance is the property of the Object Oriented Programming languages in which child class or sub class can inherit the properties of the multiple parent classes or super classes. PHP doesn't support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of cl
    4 min read

    MySQL Database

    PHP | MySQL Database Introduction
    What is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL
    4 min read
    PHP Database connection
    The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script f
    2 min read
    PHP | MySQL ( Creating Database )
    What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty,
    3 min read
    PHP | MySQL ( Creating Table )
    What is a table? In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a
    3 min read

    PHP Advance

    PHP Superglobals
    PHP superglobals are predefined variables that are globally available in all scopes. They are used to handle different types of data, such as input data, server data, session data, and more. These superglobal arrays allow developers to easily work with these global data structures without the need t
    6 min read
    PHP | Regular Expressions
    Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes a
    12 min read
    PHP Form Handling
    Form handling is the process of collecting and processing information that users submit through HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from the form. Which tool to use depends on how the form sends the data—either through the POST method (more secure, hid
    4 min read
    PHP File Handling
    In PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated c
    4 min read
    PHP | Uploading File
    Have you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types
    3 min read
    PHP Cookies
    A cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:User login status (keeping users logged in between sessions)Language preferences
    9 min read
    PHP | Sessions
    A session in PHP is a mechanism that allows data to be stored and accessed across multiple pages on a website. When a user visits a website, PHP creates a unique session ID for that user. This session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The session
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences