Programming Tutorials

public, protected, and private Methods in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

Access modifiers may also be used in conjunction with object methods, and the rules are the same:

  • public methods can be called from any scope.

  • protected methods can only be called from within one of its class methods or from within an inheriting class.

  • private methods can only be called from within one of its class methods and not from an inheriting class.

As with properties, private methods  may be redeclared by inheriting classes. Each class will see its own version of the method:

class MyDbConnectionClass {
public function connect()
$conn = $this->createDbConnection();
return $conn;

protected function createDbConnection()
return mysql_connect("localhost");

private function setDbConnection($conn)
$this->dbConnection = $conn;

private $dbConnection;


class MyFooDotComDbConnectionClass extends MyDbConnectionClass {
protected function createDbConnection()
return mysql_connect("");

This skeleton code example could be used for a database connection class. The connect() method is meant to be called by outside code. The createDbConnection() method is an internal method but enables you to inherit from the class and change it; thus, it is marked as protected. The setDbConnection() method is completely internal to the class and is therefore marked as private.

Note: When no access modifier is given for a method, public is used as the default.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in PHP )

while loops in PHP

PHP code to write to a CSV file for Microsoft Applications

Password must include both numeric and alphabetic characters - Magento

public, protected, and private Methods in PHP

Malware: global $ob_starting;

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

Cannot load /usr/local/apache/libexec/ into server:

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Warning: session_start(): open .... failed - PHP error

Convert IP address to integer and back to IP address in PHP

Function to force strict boolean values in PHP

Function to return number of digits of an integer in PHP

Latest Articles (in PHP)