


Understanding Access Modifiers in PHP OOP: Public, Protected, and Private
In PHP Object-Oriented Programming (OOP), access modifiers control the visibility of class properties and methods. The primary access modifiers in PHP are public, protected, and private.
This article will walk you through the purpose and usage of these access modifiers and explain how to apply them effectively in PHP OOP.
1. Public Access Modifier
- Keyword: public
- Visibility: Accessible from anywhere—inside the class, outside the class, and in derived classes.
- Use Case: Use public for properties or methods that should be accessible from any context.
Example:
class User { public $name = "John"; public function greet() { return "Hello, " . $this->name; } } $user = new User(); echo $user->greet(); // Output: Hello, John
In this example, both the property $name and the method greet() are public, allowing them to be accessed directly from outside the class.
2. Protected Access Modifier
- Keyword: protected
- Visibility: Accessible within the class itself and by subclasses (child classes), but not from outside the class.
- Use Case: Use protected to allow derived classes to access certain properties or methods while keeping them hidden from external code.
Example with Correct Access:
class Person { protected $age = 30; protected function getAge() { return $this->age; } } class Employee extends Person { public function showAge() { return $this->getAge(); // Correct: Accesses protected method within a subclass } } $employee = new Employee(); echo $employee->showAge(); // Output: 30
In this example, getAge() is a protected method, which is accessible within the Employee class, a subclass of Person.
Example with Error:
class Person { protected $age = 30; protected function getAge() { return $this->age; } } $person = new Person(); echo $person->getAge(); // Error: Cannot access protected method Person::getAge()
Error Message: Fatal error: Uncaught Error: Cannot access protected method Person::getAge()
In this case, trying to access the protected method getAge() directly from an instance of Person results in an error because protected methods are not accessible from outside the class.
3. Private Access Modifier
- Keyword: private
- Visibility: Only accessible within the class where it is defined. Not accessible from subclasses or external code.
- Use Case: Use private to hide properties or methods from any code outside the class, including derived classes.
Example with Correct Access:
class BankAccount { private $balance = 1000; private function getBalance() { return $this->balance; } public function showBalance() { return $this->getBalance(); // Correct: Accesses private method within the same class } } $account = new BankAccount(); echo $account->showBalance(); // Output: 1000
In this example, the getBalance() method is private, so it can only be accessed within the BankAccount class. The showBalance() method is public and can be used to indirectly access the private getBalance().
Example with Error:
class BankAccount { private $balance = 1000; private function getBalance() { return $this->balance; } } $account = new BankAccount(); echo $account->getBalance(); // Error: Cannot access private method BankAccount::getBalance()
Error Message: Fatal error: Uncaught Error: Cannot access private method BankAccount::getBalance()
In this case, trying to access the private method getBalance() directly from an instance of BankAccount results in an error because private methods are not accessible from outside the class.
Example with Error in Subclass:
class BankAccount { private $balance = 1000; private function getBalance() { return $this->balance; } } class SavingsAccount extends BankAccount { public function showBalance() { return $this->getBalance(); // Error: Cannot access private method BankAccount::getBalance() } } $savings = new SavingsAccount(); echo $savings->showBalance();
Error Message: Fatal error: Uncaught Error: Cannot access private method BankAccount::getBalance()
Here, the private method getBalance() is inaccessible even to subclasses like SavingsAccount, demonstrating that private methods cannot be accessed outside their defining class.
4. Summary of Access Modifiers
Modifier | Inside Class | Derived Class | Outside Class | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Yes | Yes | Yes | ||||||||||||||||
Protected |
Yes | Yes | No | ||||||||||||||||
Private | Yes | No | No |
- 5. Best Practices
- Use public sparingly to expose only what is necessary. Prefer encapsulation and expose functionality via public methods.
- Use protected to allow subclasses to access necessary properties or methods while hiding them from external code.
Use private to fully encapsulate class internals and prevent access from outside or derived classes.
The above is the detailed content of Understanding Access Modifiers in PHP OOP: Public, Protected, and Private. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...
