public, protected, and private Methods in PHP
By: Andi, Stig and Derick
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.
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8