public, protected, and private Properties in PHP

By: Andi, Stig and Derick Emailed: 1598 times Printed: 2042 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

A key paradigm in OOP is encapsulation and access protection of object properties (also referred to as member variables). Most common OO languages have three main access restriction keywords: public, protected, and private. When defining a class member in the class definition, the developer needs to specify one of these three access modifiers before declaring the member itself. In case you are familiar with PHP 3 or 4’s object model, all class members were defined with the var keyword, which is equivalent to public in PHP 5. var has been kept for backward compatibility, but it is deprecated, thus, you are encouraged to convert your scripts to the new keywords:

class MyClass {

public $publicMember = "Public member";

protected $protectedMember = "Protected member";

private $privateMember = "Private member";

function myMethod(){

// ...

}

}

$obj = new MyClass();

This example will be built upon to demonstrate the use of these access modifiers.

First, the more boring definitions of each access modifier:

  • public. Public members can be accessed both from outside an object by using $obj->publicMember and by accessing it from inside the myMethod method via the special $this variable (for example, $this->publicMember). If another class inherits a public member, the same rules apply, and it can be accessed both from outside the derived class’s objects and from within its methods.

  • protected. Protected members can be accessed only from within an object’s method—for example, $this->protectedMember. If another class inherits a protected member, the same rules apply, and it can be accessed from within the derived object’s methods via the special $this variable.

  • private. Private members are similar to protected members because they can be accessed only from within an object’s method. However, they are also inaccessible from a derived object’s methods. Because private properties aren’t visible from inheriting classes, two related classes may declare the same private properties. Each class will see its own private copy, which are unrelated.

Usually, you would use public for members you want to be accessible from outside the object’s scope (i.e., its methods), and private for members who are internal to the object’s logic. Use protected for members who are internal to the object’s logic, but where it might make sense for inheriting classes to  override them:

class MyDbConnectionClass {

public $queryResult;

protected $dbHostname = "localhost";

private $connectionHandle;

// ...

}

class MyFooDotComDbConnectionClass extends MyDbConnectionClass {

protected $dbHostname = "foo.com";

}

This incomplete example shows typical use of each of the three access modifiers. This class manages a database connection including queries made to the database:

  • The connection handle to the database is held in a private member, because it is used by the class’s internal logic and shouldn’t be accessible to the user of this class.

  • In this example, the database hostname isn’t exposed to the user of the class MyDbConnectionClass. To override it, the developer may inherit from the initial class and change the value.

  • The query result itself should be accessible to the developer and has, therefore, been declared as public.

Note that access modifiers are designed so that classes (or more specifi-cally, their interfaces to the outer world) always keep an is-a relationship during inheritance. Therefore, if a parent declares a member as public, the inheriting child must also declare it as public. Otherwise, the child would not have an is-a relationship with the parent, which means that anything you can do with the parent can also be done with the child.


PHP Home | All PHP Tutorials | Latest PHP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(9)


1. View Comment

This is pretty straightforward and got me to understand this basic and outline in clearly in my mind, thanks!

View Tutorial          By: Renoir Boulanger at 2009-09-01 09:49:24
2. View Comment

This is so phat. Maybe the best explanation ever to be invented and shared with the entire world wide web. It's 1998 and I love you man!

View Tutorial          By: Devin Prince III at 2010-08-11 10:01:04
3. View Comment

it's really amazing & very easy to understand & grasp the concept,thanks!!

View Tutorial          By: Vaibhav Bhalerao at 2010-08-17 10:54:52
4. View Comment

Hey, this is a great explanation regarding the differences between public, private & protected methods.

Lately I've been studying OOP & trying to improve my skills.... I was a little confused on the differences between these method types.

Your explanation has given me absolute clarity on this. I appreciate that.


View Tutorial          By: foam roofing at 2011-04-02 17:26:52
5. View Comment

Rattling explanation .....thnx brother

View Tutorial          By: zorro at 2011-06-16 05:05:43
6. View Comment

really nice

View Tutorial          By: umer at 2011-06-25 06:35:19
7. View Comment

Been looking at several website for a clear explanation of the difference. You make is so clear & easy to understand!! Thanks

View Tutorial          By: Jase at 2011-08-09 12:00:10
8. View Comment

Its super explanation

View Tutorial          By: jose at 2011-12-08 13:36:29
9. View Comment

very nice session

View Tutorial          By: Rajendra singh rathod at 2012-03-16 13:32:01

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Andi, Stig and Derick
Execution Lifetime of a PHP script
preg_split() and explode() in PHP
preg_replace() and preg_replace_callback() in PHP
preg_match(), function preg_match_all(), preg_grep() in PHP
tmpfile() in PHP
Renaming and Removing Files in PHP
Locking files in PHP
File Handling in PHP
Handling BLOB in PHP and MySQL
Using Sessions in PHP
Using Cookies in PHP
Using PEAR::Crypt_HMAC in PHP
Using HMAC Verification in PHP
Input Validation in PHP
__autoload() METHOD in PHP

More Tutorials in PHP
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Convert XML to CSV in PHP
Password must include both numeric and alphabetic characters - Magento
PHP file upload (Large Files)
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Handling file locks in PHP
HTML table output using Nested for loops in PHP
Count occurrences of a character in a String in PHP

More Latest News
Most Viewed Articles (in PHP )
A Basic Example using PHP in AWS (Amazon Web Services)
isset() function in PHP
Using Text file as database in PHP
Parent: child process exited with status 3221225477 -- Restarting
preg_split() and explode() in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Different versions of PHP - History and evolution of PHP
Function to return number of digits of an integer in PHP
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Reading .CSV file in PHP
Constants in PHP
public, protected, and private Properties in PHP
Locking files in PHP
Most Emailed Articles (in PHP)
Interfaces in PHP
Deleting Cookies in PHP
Password protecting a page in PHP
Count occurrences of a character in a String in PHP
The Object (compound) Type in PHP
History and origin of PHP
Getting Started with PHP
.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable
Different versions of PHP - History and evolution of PHP
Variables in PHP
isset() function in PHP
unset() and empty() functions in PHP
superglobals in PHP
Integers and Floating-Point Numbers in PHP
Strings in PHP