public, protected, and private Methods in PHP

By: Andi, Stig and Derick Printer Friendly Format    


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.



Ask a Question



Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial