Extend an extended class in php

Discussion in 'PHP' started by dizyn, Apr 16, 2013.

  1. #1
    Can we extend from extended class in php like this:

    class Milk extends Sheep {
        // some stuff
    }
     
    class Sheep extends Animal {
        // some stuff
    }
     
    class Animal {
        // some stuff
    }
    PHP:


    Can we inherit this way or this is not allowed? If I cannot do this, then what are possible options?
     
    dizyn, Apr 16, 2013 IP
  2. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #2
    You can absolutely extend multiple classes! Quick demo:

    <?php
     
    class Animal {
        // some stuff
    }
     
    class Mammal extends Animal {
        public function birth() {
            return'Live young';
        }
    }
     
    class Primate extends Mammal {
        public function hasBodyHair() {
            return true;
        }
    }
     
    class Human extends Primate {
        private$name;
        
        publicfunction__construct($name) {
            $this->name = $name;
        }
        
        public function getName() {
            return $this->name;
        }
        
        public function useTools() {
            return true;
        }
    }
     
     
    $human = new Human('John Doe');
    printf("Our human %s:\n", $human->getName());
    printf("\t%s tools\n", $human->useTools() ? 'uses' : 'does not use');
    printf("\t%s body hair\n", $human->hasBodyHair() ? 'has' : 'does not have');
    printf("\tgives birth to %s", $human->birth());
    PHP:
    Output:
    Our human John Doe:
       uses tools
       has body hair
       gives birth to Live young
    Code (markup):
     
    Alex Roxon, Apr 16, 2013 IP
  3. dizyn

    dizyn Active Member

    Messages:
    251
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Can you please explain with a few words why and what?
     
    dizyn, Apr 16, 2013 IP