By Adam

2010-12-05 22:13:14 8 Comments

When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?


// Public
public $variable;
public function doSomething() {
  // ...

// Private
private $variable;
private function doSomething() {
  // ...

// Protected
protected $variable;
protected function doSomething() {
  // ...


@Farzana Khan 2019-12-03 09:10:45

The mentioned keywords are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

@Sarfraz 2010-12-05 22:17:21

You use:

  • public scope to make that property/method available from anywhere, other classes and instances of the object.

  • private scope when you want your property/method to be visible in its own class only.

  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.

More: (For comprehensive information)

@Shahid 2012-05-02 08:24:42

protected scope when you want to make your variable/function visible in all classes that extend current class AND its parent classes.

@JDelage 2012-09-13 17:51:10

@Shahid - I don't understand your point. Any class that extends class A also extend A's parent class, no?

@Shahid 2012-10-18 14:06:53

@JDelage - Please see the link‌​9324

@Shahid 2012-10-19 05:48:52

@JDelage - and this link also link

@Growler 2013-03-13 18:48:04

@Safraz, Thanks for the description... but is there any harm to just making all of my methods public?

@J.Steve 2014-01-15 05:17:10

@Growler Why bother using objects at all then?

@Relaxing In Cyprus 2014-04-15 13:40:32

@Growler, a more helpful answer would be that it is good to hide as much of the inner workings of an object as possible. That way it is less likely to break. If you make everything public, then another programmer might alter a variable which you don't want changed by anything other than the inner workings of your object.

@Vladimir Despotovic 2017-02-11 21:55:13

There is no such thing as "instance of an object". There is only "instance of a class", which is an object. Please edit your answer.

@Tobias Gaertner 2019-03-27 09:40:48

"including the parent class" is IMHO misleading - it should be "including the class itself"

@Nomadme 2016-01-04 17:46:54

Public: is a default state when you declare a variable or method, can be accessed by anything directly to the object.

Protected: Can be accessed only within the object and subclasses.

Private: Can be referenced only within the object, not subclasses.

@Olaf 2010-12-05 22:17:02

private - can be accessed from WITHIN the class only

protected - can be accessed from WITHIN the class and INHERITING classes

public - can be accessed from code OUTSIDE the class as well

This applies to functions as well as variables.

@pal4life 2012-10-11 00:54:06

Not sure if the protected definition is correct here, from the actual selected answer it seems, Protected - Can be accessed only from the inherited class onwards and not from the original/parent class. Saying "WITHIN the class" can be a bit confusing.

@Olaf 2012-10-11 06:40:24

I don't think so, in fact it seems that the selected answer is the one that is confusing here. See Shahids comment. IMHO a protected method can very well be accessed from within the original class.

@Serjas 2012-11-08 09:59:31

can a class can access another class's public?

@DanMan 2013-08-18 10:02:54

@Serjas: No, only another object's, unless they're static methods/fields.

@John Slegers 2015-03-19 00:36:33

I don't know if this applies to all programming languages, but in PHP "protected" properties / methods can be accessed in either the class in which it has been declared or classes that inherit from the class defining the property / method.

@Mahedi Hasan Durjoy 2019-01-18 08:25:39

When we follow object oriented php in our project , we should follow some rules to use access modifiers in php. Today we are going to learn clearly what is access modifier and how can we use it.PHP access modifiers are used to set access rights with PHP classes and their members that are the functions and variables defined within the class scope. In php there are three scopes for class members.


Now, let us have a look at the following image to understand access modifier access level enter image description here

Now, let us have a look at the following list to know about the possible PHP keywords used as access modifiers.

public :- class or its members defined with this access modifier will be publicly accessible from anywhere, even from outside the scope of the class.

private :- class members with this keyword will be accessed within the class itself. we can’t access private data from subclass. It protects members from outside class access.

protected :- same as private, except by allowing subclasses to access protected superclass members.

Now see the table to understand access modifier Read full article php access modifire

@Shankar Damodaran 2014-02-20 08:35:40



When you declare a method (function) or a property (variable) as public, those methods and properties can be accessed by:

  • The same class that declared it.
  • The classes that inherit the above declared class.
  • Any foreign elements outside this class can also access those things.



class GrandPa
    public $name='Mark Henry';  // A public variable

class Daddy extends GrandPa // Inherited class
    function displayGrandPaName()
        return $this->name; // The public variable will be available to the inherited class


// Inherited class Daddy wants to know Grandpas Name
$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

// Public variables can also be accessed outside of the class!
$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Prints 'Mark Henry'


When you declare a method (function) or a property (variable) as protected, those methods and properties can be accessed by

  • The same class that declared it.
  • The classes that inherit the above declared class.

Outsider members cannot access those variables. "Outsiders" in the sense that they are not object instances of the declared class itself.



class GrandPa
    protected $name = 'Mark Henry';

class Daddy extends GrandPa
    function displayGrandPaName()
        return $this->name;


$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error

The exact error will be this:

PHP Fatal error: Cannot access protected property GrandPa::$name


When you declare a method (function) or a property (variable) as private, those methods and properties can be accessed by:

  • The same class that declared it.

Outsider members cannot access those variables. Outsiders in the sense that they are not object instances of the declared class itself and even the classes that inherit the declared class.



class GrandPa
    private $name = 'Mark Henry';

class Daddy extends GrandPa
    function displayGrandPaName()
        return $this->name;


$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Results in a Notice 

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error

The exact error messages will be:

Notice: Undefined property: Daddy::$name
Fatal error: Cannot access private property GrandPa::$name

Dissecting the Grandpa Class using Reflection

This subject is not really out of scope, and I'm adding it here just to prove that reflection is really powerful. As I had stated in the above three examples, protected and private members (properties and methods) cannot be accessed outside of the class.

However, with reflection you can do the extra-ordinary by even accessing protected and private members outside of the class!

Well, what is reflection?

Reflection adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. Additionally, they offers ways to retrieve doc comments for functions, classes and methods.


We have a class named Grandpas and say we have three properties. For easy understanding, consider there are three grandpas with names:

  • Mark Henry
  • John Clash
  • Will Jones

Let us make them (assign modifiers) public, protected and private respectively. You know very well that protected and private members cannot be accessed outside the class. Now let's contradict the statement using reflection.

The code


class GrandPas   // The Grandfather's class
    public     $name1 = 'Mark Henry';  // This grandpa is mapped to a public modifier
    protected  $name2 = 'John Clash';  // This grandpa is mapped to a protected  modifier
    private    $name3 = 'Will Jones';  // This grandpa is mapped to a private modifier

# Scenario 1: without reflection
$granpaWithoutReflection = new GrandPas;

# Normal looping to print all the members of this class
echo "#Scenario 1: Without reflection<br>";
echo "Printing members the usual way.. (without reflection)<br>";
foreach($granpaWithoutReflection as $k=>$v)
    echo "The name of grandpa is $v and he resides in the variable $k<br>";

echo "<br>";

#Scenario 2: Using reflection

$granpa = new ReflectionClass('GrandPas'); // Pass the Grandpas class as the input for the Reflection class
$granpaNames=$granpa->getDefaultProperties(); // Gets all the properties of the Grandpas class (Even though it is a protected or private)

echo "#Scenario 2: With reflection<br>";
echo "Printing members the 'reflect' way..<br>";

foreach($granpaNames as $k=>$v)
    echo "The name of grandpa is $v and he resides in the variable $k<br>";


#Scenario 1: Without reflection
Printing members the usual way.. (Without reflection)
The name of grandpa is Mark Henry and he resides in the variable name1

#Scenario 2: With reflection
Printing members the 'reflect' way..
The name of grandpa is Mark Henry and he resides in the variable name1
The name of grandpa is John Clash and he resides in the variable name2
The name of grandpa is Will Jones and he resides in the variable name3

Common Misconceptions:

Please do not confuse with the below example. As you can still see, the private and protected members cannot be accessed outside of the class without using reflection


class GrandPas   // The Grandfather's class
    public     $name1 = 'Mark Henry';  // This grandpa is mapped to a public modifier
    protected  $name2 = 'John Clash';  // This grandpa is mapped to a protected modifier
    private    $name3 = 'Will Jones';  // This grandpa is mapped to a private modifier

$granpaWithoutReflections = new GrandPas;


GrandPas Object
    [name1] => Mark Henry
    [name2:protected] => John Clash
    [name3:GrandPas:private] => Will Jones

Debugging functions

print_r, var_export and var_dump are debugger functions. They present information about a variable in a human-readable form. These three functions will reveal the protected and private properties of objects with PHP 5. Static class members will not be shown.

More resources:

@JamesG 2017-03-18 11:12:23

apologies for the late add on to this convo. Can you tell me why someone would use these? You have explained perfectly how they work etc.. I just would like to know the benefits of use for each of these. Thank you

@cjmling 2017-05-05 15:58:01

@JamesG its a bit explained in the other comment above.…

@bxN5 2017-06-06 14:43:39

I don't know why maybe it's a little out of this question but no one mentioned that in PHP there are another two access modifiers: abstract and final this keyword can be used only for PHP classes but it still access modifiers

@Julio Marchi 2017-10-14 14:42:53

I would suggest you read the explanation about abstraction provided by Dhairya Lakhera here:…. It is a perfect addition to Shankar Damodaran explanations.

@DanMan 2012-05-28 14:27:42

Considering 'when':
I tend to declare everything as private initially, if I'm not exactly sure. Reason being, that it's usually much easier to turn a private method public than the other way round. That's because you can at least be sure that the private method hasn't been used anywhere but in the class itself. A public method may already be in use everywhere, possibly requiring an extensive re-write.

Update: i go for a default of protected nowadays, because I've come to find that it's good enough for encapsulation and doesn't get in the way when I'm extending classes (which i try to avoid anyway). Only if i have a good reason to use the other two, i will.

A good reason for a private method would be one that implements something inherent to that object that even an extending class should not change (factual reason, in addition to encapsulation, like internal state management). Eventually, it's still easy enough to track down where a protected method is being used usually, so i default to protected nowadays. Maybe not 100% objective "in the trenches" experience, I admit.

@hakre 2013-10-06 08:02:43

With your update: Can you make more clear how "good enough" and "good reason" go together here? For example, using private would be still "good enough" to use, but you don't suggest that any longer albeit the earlier reasons you gave sound like a "good reason" still: encapsulation.

@DanMan 2017-10-13 12:07:01

@hakre: The reason why we ought to strive for encapsulation is to avoid leaking state into the outer scope. protected does that already, but you keep it flexible for extension/inheritance. Again, unless you have a good reason to make it private.

@hakre 2017-10-14 09:34:21

Well that is probably the point we disagree: protected actually leaks into outer scope and is often in your way as it supports bad design decisions like implicitly favoring inheritance while it's better to favor composition. That's why sticking with private unless you have actual requirements not to is often a better way to start writing code. This will also prevent to make design decisions too early while they are actually not yet needed.

@DanMan 2017-10-14 10:52:12

I won't argue with your overall point, because it's fair enough, but protected doesn't leak into outer scope (code that's calling/accessing the method/field) but only inner scope (extending classes). There's a difference, as minor as it may be to you. It's much easier to track down usage of a protected field than a public one.

@Ahmad Awais 2016-06-30 07:27:52

⚡️ Here is an easy way to remember the scope of public, protected and private.


  • public scope: A public variable/function is available to both objects and other classes.


  • protected scope: A protected variable/function is available to all the classes that extend the current class.
  • No! Objects cannot access this scope


  • private scope: A private variable/function is only visible in the current class where it is being defined.
  • No! Class that extend the current class cannot access this scope.
  • No! Objects cannot access this scope.

Read the Visibility of a method or variable on PHP Manual.

@mcfedr 2016-11-16 09:51:18

Reviving an old question, but I think a really good way to think of this is in terms of the API that you are defining.

  • public - Everything marked public is part of the API that anyone using your class/interface/other will use and rely on.

  • protected - Don't be fooled, this is also part of the API! People can subclass, extend your code and use anything marked protected.

  • private - Private properties and methods can be changed as much as you like. No one else can use these. These are the only things you can change without making breaking changes.

Or in Semver terms:

  • Changes to anything public or protected should be considered MAJOR changes.

  • Anything new public or protected should be (at least) MINOR

  • Only new/changes to anything private can be PATCH

So in terms of maintaining code, its good to be careful about what things you make public or protected because these are the things you are promising to your users.

@Andrew 2016-01-25 03:16:10

For me, this is the most useful way to understand the three property types:

Public: Use this when you are OK with this variable being directly accessed and changed from anywhere in your code.

Example usage from outside of the class:

$myObject = new MyObject()
$myObject->publicVar = 'newvalue';
$pubVar = $myObject->publicVar;

Protected: Use this when you want to force other programmers (and yourself) to use getters/setters outside of the class when accessing and setting variables (but you should be consistent and use the getters and setters inside the class as well). This or private tend to be the default way you should set up all class properties.

Why? Because if you decide at some point in the future (maybe even in like 5 minutes) that you want to manipulate the value that is returned for that property or do something with it before getting/setting, you can do that without refactoring everywhere you have used it in your project.

Example usage from outside of the class:

$myObject = new MyObject()
$protectedVar = $myObject->getProtectedVar();

Private: private properties are very similar to protected properties. But the distinguishing feature/difference is that making it private also makes it inaccessible to child classes without using the parent class's getter or setter.

So basically, if you are using getters and setters for a property (or if it is used only internally by the parent class and it isn't meant to be accessible anywhere else) you might as well make it private, just to prevent anyone from trying to use it directly and introducing bugs.

Example usage inside a child class (that extends MyObject):

$privateVar = $this->getPrivateVar();

@Suman K.C 2014-02-07 03:07:44

Visibility Scopes with Abstract Examples :: Makes easy Understanding

This visibility of a property or method is defined by pre-fixing declaration of one of three keyword (Public, protected and private)

Public : If a property or method is defined as public, it means it can be both access and manipulated by anything that can refer to object.

  • Abstract eg. Think public visibility scope as "public picnic" that anybody can come to.

Protected : when a property or method visibility is set to protected members can only be access within the class itself and by inherited & inheriting classes. (Inherited:- a class can have all the properties and methods of another class).

  • Think as a protected visibility scope as "Company picnic" where company members and their family members are allowed not the public. It's the most common scope restriction.

Private : When a property or method visibility is set to private, only the class that has the private members can access those methods and properties(Internally within the class), despite of whatever class relation there maybe.

  • with picnic analogy think as a "company picnic where only the company members are allowed" in the picnic. not family neither general public are allowed.

@Techie 2013-10-03 11:01:26

 * Define MyClass
class MyClass
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
        echo $this->public;
        echo $this->protected;
        echo $this->private;

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

 * Define MyClass2
class MyClass2 extends MyClass
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
        echo $this->public;
        echo $this->protected;
        echo $this->private;

$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined

Extracted From :

@star18bit 2013-03-15 08:25:49

Variables in PHP are cast in three different type:

Public : values of this variable types are available in all scope and call on execution of you code. declare as: public $examTimeTable;

Private: Values of this type of variable are only available on only to the class it belongs to. private $classRoomComputers;

Protected: Values of this class only and only available when Access been granted in a form of inheritance or their child class. generally used :: to grant access by parent class

protected $familyWealth;

@Matthew Watts 2012-09-03 19:51:16

The difference is as follows:

Public :: A public variable or method can be accessed directly by any user of the class.

Protected :: A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

Private :: A private variable or method can only be accessed internally from the class in which it is defined.This means that a private variable or method cannot be called from a child that extends the class.

@The Awnry Bear 2012-09-03 20:17:17

It is typically considered good practice to default to the lowest visibility required as this promotes data encapsulation and good interface design. When considering member variable and method visibility think about the role the member plays in the interaction with other objects.

If you "code to an interface rather than implementation" then it's usually pretty straightforward to make visibility decisions. In general, variables should be private or protected unless you have a good reason to expose them. Use public accessors (getters/setters) instead to limit and regulate access to a class's internals.

To use a car as an analogy, things like speed, gear, and direction would be private instance variables. You don't want the driver to directly manipulate things like air/fuel ratio. Instead, you expose a limited number of actions as public methods. The interface to a car might include methods such as accelerate(), deccelerate()/brake(), setGear(), turnLeft(), turnRight(), etc.

The driver doesn't know nor should he care how these actions are implemented by the car's internals, and exposing that functionality could be dangerous to the driver and others on the road. Hence the good practice of designing a public interface and encapsulating the data behind that interface.

This approach also allows you to alter and improve the implementation of the public methods in your class without breaking the interface's contract with client code. For example, you could improve the accelerate() method to be more fuel efficient, yet the usage of that method would remain the same; client code would require no changes but still reap the benefits of your efficiency improvement.

Edit: Since it seems you are still in the midst of learning object oriented concepts (which are much more difficult to master than any language's syntax), I highly recommend picking up a copy of PHP Objects, Patterns, and Practice by Matt Zandstra. This is the book that first taught me how to use OOP effectively, rather than just teaching me the syntax. I had learned the syntax years beforehand, but that was useless without understanding the "why" of OOP.

@Josiah 2014-12-30 01:48:17

The book recommended in the edit of this post is really very excellent. The chunk I so far has proved quite enlightening. The first few chapters answered most of my class-related questions.

@Patanjali 2016-04-03 10:02:09

The books that allowed me to really understand objects, without crowding out my thinking with unnecessary details, like examples in Smalltalk, were by David A Taylor, being Object Oriented Technology: A Manager's Guide and Business Engineering with Object Teechnology. Both are only 100 pages, and each easy enough to read in an afternoon. Of course, there is Gamma et al's Design Patterns, though the basic approach can simply be described by 'subclass what you want to vary'.

@Jānis Elmeris 2018-03-11 21:32:48

A very nice analogy. Do you have one for protected vs private?

@Mchl 2010-12-05 22:22:42

They're there to allow for different levels of encapsulation

@Aaron Hall 2016-11-10 22:23:59

You could probably flesh this out a little.

@code_burgar 2010-12-05 22:16:37

PHP manual has a good read on the question here.

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] What are metaclasses in Python?

20 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

35 Answered Questions

[SOLVED] Interface vs Abstract Class (general OO)

28 Answered Questions

37 Answered Questions

[SOLVED] What is the difference between an interface and abstract class?

23 Answered Questions

[SOLVED] When to use self over $this?

  • 2008-09-30 06:23:06
  • Casey Watson
  • 705125 View
  • 2010 Score
  • 23 Answer
  • Tags:   php class oop scope

26 Answered Questions

[SOLVED] Difference between staticmethod and classmethod

8 Answered Questions

27 Answered Questions

Sponsored Content