Friday 14 May 2021

Php: Access specifiers (or) visibility modifiers

 

Access specifiers (or) visibility modifiers are used to control the access to properties, methods of an object.

 

Php support 3 access modifiers.

a.   public: Any property/method defined with this access modifier can be accessed from anywhere.

b.   protected: Any property/method defined with this access modifier can be accessed from this class and its subclasses.

c.    Private: Any property/method defined with this access modifier can be accessed within the class only.

 

 

How to define a method with access specifiers?

‘public’, ‘protected’ and ‘private’ keywords are used to define methods with controlled access. Just prepend the method with access specifiers.

 

Example

public function m1(){

 

}

 

Let’s define a class with

a.   One private method.

b.   One public method

c.    One protected method

class ParentClass{

    public function i_am_public(){
        echo "\nIn public method";
    }

    protected function i_am_protected(){
        echo "\nIn protected method";
    }

    private function i_am_private(){
        echo "\nIn private method";
    }
}

 

Since ‘i_am_public()’ method is defined with public access specifier, you can access it outside the class, but not others.

 

$p1 = new ParentClass();

$p1->i_am_public();

 

But when you try to access protected, private methods via object from outside of the class, you will get an error.

 

As I said earlier, you can access a protected method from subclass.

class ChildClass extends ParentClass{

    function call_super_class_methods(){
        $this->i_am_public();
        $this->i_am_protected();
        // $this->i_am_private(); Do not run
    }
}

 

You can access both public and protected methods from sub class, but not the private methods.

 

Find the below working application.

 

access_specifiers_demo.php

 

#!/usr/bin/php

<?php

    class ParentClass{

        public function i_am_public(){
            echo "In public method\n";
        }

        protected function i_am_protected(){
            echo "In protected method\n";
        }

        private function i_am_private(){
            echo "In private method\n";
        }
    }

    class ChildClass extends ParentClass{

        function call_super_class_methods(){
            $this->i_am_public();
            $this->i_am_protected();
            // $this->i_am_private(); Do not run
        }
    }

    $p1 = new ParentClass();
    $p1->i_am_public();
   // $p1->i_am_protected(); Do not run
   // $p1->i_am_private();  Do not run

    $c1 = new ChildClass();
    $c1 -> call_super_class_methods();

?>

 

Output

$./access_specifiers_demo.php 

In public method
In public method
In protected method

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment