In PHP object-oriented programming, a function's access level determines which parts of the code can call it. By setting access modifiers, developers can flexibly control the visibility and accessibility of functions, enhancing security and encapsulation.
Functions declared as public are accessible from any code, both inside and outside the class.
public function publicFunction() {
// function code
}
Functions declared as protected can only be accessed within the class they are defined in and its subclasses. They cannot be accessed from outside these classes.
protected function protectedFunction() {
// function code
}
Functions declared as private are only accessible within the class they are defined in. Neither subclasses nor external code can access them.
private function privateFunction() {
// function code
}
The following example demonstrates how functions with different access levels behave in parent and child classes:
class ParentClass {
public function publicFunction() {
echo "Public function in parent class";
}
protected function protectedFunction() {
echo "Protected function in parent class";
}
private function privateFunction() {
echo "Private function in parent class";
}
}
class ChildClass extends ParentClass {
public function accessFunctions() {
$this->publicFunction();
$this->protectedFunction();
// The following call will cause an error because privateFunction is private
// $this->privateFunction();
}
}
$child = new ChildClass();
$child->publicFunction();
$child->protectedFunction(); // This will cause an error because protected functions cannot be accessed outside the class
In this example, the ParentClass defines functions with different access levels. The subclass ChildClass can access the public and protected functions of the parent but cannot access the private function. Note that protected functions cannot be called directly from outside the class.
Using access modifiers properly is a fundamental part of PHP object-oriented design. By correctly specifying function access levels, you can protect internal implementation details of a class while exposing necessary interfaces to the outside, achieving encapsulation and code reuse effectively.