Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - extend method like extending a class

Tags:

php

class

extends

I have 2 class:

class animal{
    public function walk(){
        walk;
    }
}

class human extends animal{
    public function walk(){
        with2legs;
    }
}

This way, if i call human->walk(), it only runs with2legs;

But I want the run the parent's walk; too.

I know I can modify it this way:

class human extends animal{
    public function walk(){
        parent::walk();
        with2legs;
    }
}

But the problem is, I have many subclasses and I don't want to put parent::walk(); into every child walk(). Is there a way I can extend a method like I extend a class? Without overriding but really extending the method. Or is there better alternatives?

Thanks.

like image 642
Tony Avatar asked Jun 18 '13 03:06

Tony


People also ask

Can a method extend a class?

You can extend the class and override just the single method you want to "extend".

Can you extend 2 classes in PHP?

Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.

What is purpose of $this and extends in PHP?

Definition and Usage The extends keyword is used to derive a class from another class. This is called inheritance. A derived class has all of the public and protected properties of the class that it is derived from.

What is the difference between extends and implements in PHP?

Extends : This is used to get attributes of a parent class into base class and may contain already defined methods that can be overridden in the child class. Implements : This is used to implement an interface (parent class with functions signatures only but not their definitions) by defining it in the child class.


1 Answers

I would use "hook" and abstraction concepts :

class animal{

    // Function that has to be implemented in each child
    abstract public function walkMyWay();

    public function walk(){
        walk_base;
        $this->walkMyWay();
    }
}

class human extends animal{
    // Just implement the specific part for human
    public function walkMyWay(){
        with2legs;
    }
}

class pig extends animal{
    // Just implement the specific part for pig
    public function walkMyWay(){
        with4legs;
    }
}

This way I just have to call :

// Calls parent::walk() which calls both 'parent::walk_base' and human::walkMyWay()
$a_human->walk();      
// Calls parent::walk() which calls both 'parent::walk_base' and pig::walkMyWay()
$a_pig->walk();

to make a child walk his way...


See Template method pattern.


like image 89
Gauthier Boaglio Avatar answered Oct 09 '22 21:10

Gauthier Boaglio