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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Final >>

Previous chapter: Private

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.