Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Visibility Scope Of Variable And Functions

    • 0
    • 2
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 362
    Comment on it

    There are three type of visibility scope:

    1. Public
    2. Private
    3. Protected

    PUBLIC:

    Variable or function of public scope can be accessed throughout the program.

    PRIVATE :

    Variable or function of private scope can be accessed only with in the class they are declared.

    PROTECTED:

    Variable or function of protected scope can be accessed only by its subclass and derived class.

    <?php
    /**
     * Define ClassA
     */
    class ClassA
    {
        public $a = 1;
        protected $b = 2;
        private $c = 3;
    
        function detail()
        {
            echo $this->a;
            echo $this->b;
            echo $this->c;
        }
    }
    
    $obj = new ClassA();
    echo $obj->a; // Works
    echo $obj->b; // Fatal Error
    echo $obj->c; // Fatal Error
    $obj->detail(); // Shows Public, Protected and Private
    
    
    /**
     * Define ClassB
     */
    class ClassB extends ClassA
    {
        // We can redeclare the public and protected method, but not private
        protected $b = '4';
    
        function detail()
        {
            echo $this->a;
            echo $this->b;
            echo $this->c;
        }
    }
    
    $obj2 = new ClassB();
    echo $obj2->a; // Works
    echo $obj2->b; // Fatal Error
    echo $obj2->c; // Undefined
    $obj2->detail(); // Shows Public, Protected2, Undefined
    
    ?>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: