Understanding Public, Private, and Protected Methods in PHP

Rumman Ansari   Software Engineer   2024-07-18 09:10:31   5555  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Methods can be public, private or protected. Public means that methods can be accessed everywhere, private means methods can be accessed by the class that defines the member and protected means methods can be accessed only within the class itself and by inherited and parent classes.

Example:

Syntax



<?php
// Define a class
class Myclass
 {
 // Declare a public method public function my_public_method()
 {
 echo "This is a Public method"; 
 } 
 private function my_private_method()
 {
 echo "This is a Private method"; 
 }
 protected function my_protected_method()
 {
 echo "This is a Protected method"; 
 } 
 // This is public
 function test()
 {
 $this->my_public_method();
 $this->my_private_method();
 $this->my_protected_method();
 }
 }
 $obj = new MyClass;
 $obj->my_public_method(); //Display This is a Public method
 $obj->my_private_method();//Fatal error: Call to private method Myclass::my_private_method() from context '' in F:\wamp\www..
 $obj>my_protected_method();//Fatal error: Call to undefined function my_protected_method() in F:\wamp\www..
 $obj->test(); //Display This is a Public methodThis is a Private methodThis is a Protected method
?>



Note: PHP uses inheritance in it's object model and when you extend a class, the subclass inherits all of the public and protected methods from the parent class. When we will discuss the inheritance, you will get more information about protected properties and methods.