


Scope vs. Visibility: Understanding `public`, `protected`, and `private` in PHP OOP
Jul 28, 2025 am 04:40 AMPublic members can be accessed within, outside and in subclasses; 2. The protected members are only accessed within and in subclasses, and cannot be accessed from outside; 3. The private members are only accessed within the class that defines them, and are not accessible from the subclass and outside; correct use of these three access modifiers can effectively implement encapsulation, improving the security, maintainability and reusability of the code.
When working with object-oriented programming (OOP) in PHP, understanding the difference between scope and visibility is essential for writing clean, secure, and maintainable code. While these terms are sometimes used interchangeably, they refer to slightly different concepts:

- Scope refers to where a variable or method can be accessed (eg, inside a class, outside, in child classes).
- Visibility (also called access control ) refers to how accessible a property or method is — controlled by keywords like
public
,protected
, andprivate
.
Let's break down how public
, protected
, and private
work in PHP and how they affect both scope and visibility.
What Are Visibility Modifiers?
PHP provides three visibility keywords to control access to class members (properties and methods):

Modifier | Accessible From |
---|---|
public
|
Anywhere (inside class, outside, in child classes) |
protected
|
Inside the class and its child (inherited) classes only |
private
|
Only within the same class (not even in child classes) |
These modifiers define who can access a property or method — that's the core of visibility.
public
: No Restrictions
A public
member can be accessed from anywhere — inside the class, outside the class via an object, and in any child class.

class User { public $name = "John"; public function getName() { return $this->name; } } $user = new User(); echo $user->name; // Works: John echo $user->getName(); // Works: John
? Use public
when you want a property or method to be freely accessible.
?? Overusing
public
can lead to poor encapsulation. It's generally better to make propertiesprivate
and expose them viapublic
getter/setter methods if needed.
protected
: Internal Inherited Access
protected
members can be accessed:
- Inside the class that defines them
- Inside any child class (via inheritance)
- But not from outside the object
class User { protected $name = "John"; protected function getName() { return $this->name; } } class Admin extends User { public function display() { return $this->getName(); // OK: inherited access } } $admin = new Admin(); echo $admin->display(); // Works: John $user = new User(); echo $user->name; // Fatal error: Cannot access protected property
? Use protected
when you want to allow subclasses to use or override behavior but hide it from external code.
This is common with methods means to be extended or helper functions used across a class hierarchy.
private
: Class-Only Access
private
members are only accessible within the class where they are defined. Even child classes cannot access them.
class User { private $password = "secret123"; private function hashPassword($pass) { return md5($pass); } public function setPassword($pass) { $this->password = $this->hashPassword($pass); } } class Admin extends User { public function showPassword() { // echo $this->password; // Fatal error: Cannot access private property } }
? Use private
to fully encapsulate internal logic or sensitive data. This prevents accidental or intentional misuse from subclasses or external code.
? Think of
private
as "internal use only" — ideal for helper methods, configuration, or data that shouldn't leak.
Key Differences Summary
Visibility | Same Class | Child Class | Outside Object |
---|---|---|---|
public | ? Yes | ? Yes | ? Yes |
protected | ? Yes | ? Yes | ? No |
private | ? Yes | ? No | ? No |
Note: There's no friend
concept in PHP (like in C ), so no way to grant special access to other classes.
Best Practices
- Make properties
private
by default — expose them viapublic
getters/setters if needed. - Use
protected
for methods intended to be reused or overridden in child classes. - Avoid
public
properties — they break encapsulation and make your class harder to maintain. - Use visibility to enforce encapsulation , one of the core OOP principles.
For example:
class User { private $email; public function getEmail() { return $this->email; } public function setEmail($email) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->email = $email; } else { throw new InvalidArgumentException("Invalid email"); } } }
Here, we control how the email is set — something impossible with a public
property.
Understanding public
, protected
, and private
isn't just about syntax — it's about designing robust, reusable, and secure classes . Choosing the right visibility helps you define clear boundaries and protect your object's internal state.
Basically:
-
public
= anyone can use it -
protected
= only us and our kids -
private
= strictly internal
Get this right, and your OOP will be much stronger.
The above is the detailed content of Scope vs. Visibility: Understanding `public`, `protected`, and `private` in PHP OOP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP's hyperglobal variables are always available built-in arrays used to process request data, manage state and obtain server information; 1. When using $_GET, URL parameters need to be type-converted and verified; 2. When receiving form data through $_POST, filtering should be performed with filter_input(); 3. Avoid using $_REQUEST to prevent security vulnerabilities; 4. $_SESSION needs to call session_start() and log in to reset the session ID; 5. When setting $_COOKIE, enable secure, httponly and samesite attributes; 6. The information in $_SERVER cannot be fully trusted and cannot be used for security verification; 7.$_ENV may be

Thedifferencebetweenlocalandglobalscopeliesinwherevariablesaredeclaredandaccessible:globalvariablesaredefinedoutsidefunctionsandaccessibleeverywhere,whilelocalvariablesaredeclaredinsidefunctionsandonlyaccessiblewithinthem.1.Globalscopeallowsbroadacce

In PHP, if you want to use external variables in anonymous functions, you must explicitly import them through the use keyword; 1. Use is used to introduce external variables into the lexical scope of the closure; 2. Pass variables by default by value, and pass them by reference with &$var syntax; 3. Multiple variables can be imported, separated by commas; 4. The value of the variable is captured when the closure is defined, not when it is executed; 5. Each iteration in the loop creates an independent closure copy to ensure that the variable value is correctly captured; therefore, use is a key mechanism to achieve the interaction between the closure and the external environment, making the code more flexible and controllable.

ThetwomaintoolsforaccessingglobalvariablesinPHParetheglobalkeywordandthe$GLOBALSsuperglobalarray;1)Theglobalkeywordcreatesareferencetoaglobalvariableinsideafunction,allowingdirectaccessandmodification,andifthevariableisundefined,itinitializesitasnull

PHPresolvesvariablesinaspecificorder:1.Localscopewithinthecurrentfunction,2.Functionparameters,3.Variablesimportedviauseinclosures,4.Globalscopeonlyifexplicitlydeclaredwithglobaloraccessedthrough$GLOBALS,5.Superglobalslike$_SESSIONand$_POSTwhichareal

Functions using yield will become generators, and when called, they return the generator object instead of being executed immediately; 2. Local variables of the generator will not be destroyed during the yield pause, but will continue to exist with the generator frame until the generator is exhausted or closed; 3. Extended variable life cycle may lead to an increase in memory usage, especially when referring to large objects; 4. When combined with closures, LEGB rules are still followed, but the latebinding problem of looping variables needs to be solved by immediately binding (such as the default parameter value); 5. .close() should be called explicitly to ensure that finally block execution is performed to avoid delays in resource cleaning. The generator affects memory and behavior by extending the survival time of variables, but does not change the lexical scope rules.

Variablesdisappearduetoscoperules—wherethey’redeclareddetermineswheretheycanbeaccessed;2.Accidentalglobalcreationoccurswhenomittingvar/let/const,whilestrictmodepreventsthisbythrowingerrors;3.Blockscopeconfusionarisesbecausevarisfunction-scoped,unlike

TheglobalkeywordinPHPallowsfunctionstoaccessvariablesfromtheglobalscope,butitshouldbeusedsparinglyduetosignificantdrawbacks.1)Itenablesquickaccesstoconfigurationvaluesinsmallorlegacyscripts.2)ItfitsproceduralcodebaseslikeolderWordPresspluginswheredep
