Protected

Variables and functions marked as protected are accessible only through the object that owns them, whether or not they are declared in that object's class or whether they have descended from a parent class. Consider the following code:

<?php
    
class dog {
        public
$Name;
        private function
getName() {
            return
$this->Name;
        }
    }

    class
poodle extends dog {
        public function
bark() {
            print
"'Woof', says " . $this->getName();
        }
    }
    
    
$poppy = new poodle;
    
$poppy->Name = "Poppy";
    
$poppy->bark();
?>

In that code, the class poodle extends from class dog, class dog has a public variable $Name and a private function getName(), and class poodle has a public function called bark(). So, we create a poodle, give it a $Name value of "Poppy" (the $Name variable comes from the dog class), then ask it to bark(). The bark() function is public, which means we can call it as shown above, so this is all well and good.

However, note that the bark() function calls the getName() function, which is part of the dog class and was marked private - this will stop the script from working, because private variables and functions cannot be accessed from inherited classes. That is, we cannot access private dog functions and variables from inside the poodle class.

Now try changing bark() to protected, and all should become clear - the variable is still not available to the world as a whole, but handles inheritance as you would expect, which means that we can access getName() from inside poodle.

 

Next chapter: Final >>

Previous chapter: Private

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar