Using Protected Inheritance


You've seen that public properties and methods are available outside an object, and that private properties and methods are not. But when you make properties or methods protected, they're restricted to the current class, or any classes derived from the current class. For example, if you were to make the Animal class's set_name method protected and then tried to call it from a Lion object, it wouldn't work because it's protected:

 class animal {     var $name;     protected function set_name($text)     {         $this->name = $text;     }     function get_name()     {         return $this->name;     } } echo "Creating your new lion...<BR>"; $lion = new Lion; $lion->set_name("Leo");                        // Won't work! $lion->roar(); 

Here's the error you get:

[View full width]

PHP Fatal error: Call to protected method animal::set_name() from context in phpprotected .php on line 48

On the other hand, the protected set_name method is available in the code for both the Animal and Lion classes, so if you simply make the Lion class's constructor call this method to set the name, there'll be no problem, as you see in phpprotected.php, Example 7-3.

Example 7-3. Using protected inheritance, phpprotected.php
 <HTML>     <HEAD>         <TITLE>Using protected inheritance</TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Using protected inheritance</H1>             <?php                 class animal                 {                     var $name;                     protected function set_name($text)                     {                         $this->name = $text;                     }                     function get_name()                     {                         return $this->name;                     }                 }                 class Lion extends Animal                 {                     var $name;                     function roar()                     {                         echo $this->name, " is roaring!<BR>";                     }                     function _ _construct($text)                     {                         $this->set_name($text);                     }                 }                 echo "Creating your new lion...<BR>";                 $lion = new Lion("Leo");                 $lion->roar();             ?>         </CENTER>     </BODY> </HTML> 

You can see the results in Figure 7-3.

Figure 7-3. Using protected inheritance.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net