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();
$this->setDbConnection($conn);
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("foo.com");
}
}

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
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Send push notifications using Expo tokens in PHP

Encrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

A Basic Example using PHP in AWS (Amazon Web Services)

Decrypting files using GnuPG (GPG) via PHP

Parent: child process exited with status 3221225477 -- Restarting

Error: Length parameter must be greater than 0

Password must include both numeric and alphabetic characters - Magento

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Convert XML to CSV in PHP

Count occurrences of a character in a String in PHP

PHP file upload prompts authentication for anonymous users

Latest Articles (in PHP)