samedi 18 janvier 2020

What are the limitations of inheriting from abstract class that are remedied by traits in PHP?

I have been reading about traits, interfaces and abstract classes from php Manuel(php.net) and some relevant posts on stackoverflow. E.g. Reading these two posts in particular

https://stackoverflow.com/a/20866390/3429430
https://stackoverflow.com/a/39466629/3429430

The main point being made is, with abstract class you get the object oriented inheritance properties along with, which are unnecessary. Using traits won't bring those inheritance issues. My question is, please provide a technical example where we see inheritance problems which obscure the programming logic and then how traits in that piece of code removes those obstructions.

I have tried to conceive the following example and I do not see any limitation brought by inheritance which can be removed by traits:

// example of Cartesian system involving line, triangle etc
trait distance {
    function x_diff($x1, $x2) {
        return abs($x1-$x2);
    }
    function y_diff($y1,$y2) {
        return abs($y1-$y2);
    }
    function length($x1,$x2,$y1,$y2) {
        return sqrt(pow(($x1-$x2),2) + pow(($y1-$y2),2));
    }
}

abstract class myDistance {
    function x_diff($x1, $x2) {
        return abs($x1-$x2);
    }
    function y_diff($y1,$y2) {
        return abs($y1-$y2);
    }
    function length($x1,$x2,$y1,$y2) {
        return sqrt(pow(($x1-$x2),2) + pow(($y1-$y2),2));
    }
}

class triangle extends myDistance {
    public $point1 = [];
    public $point2 = [];
    public $point3 = [];

    // All the methods inherited from myDistance class will 
    // come handy to find area, angle betwwen adjecent sidea etc

    public function area($point1,$point2,$point3) {
        // code to find the area...
    }

    //other functions to find other properties of the triangle...

}

class line {
    use distance; //{class line extends myDistance} would be the same thing
                  //What limitations would inhertence have imposed?
    public $point1 = [];
    public $point2 = [];

    // All the methods copied from distance trait will 
    // come handy to find area, angle betwwen adjecent sidea etc

    public function angleToXaxis($point1,$point2) {
        //code to find angle of inclination...
    }

    //other functions to find other properties

}

Cheers.

Aucun commentaire:

Enregistrer un commentaire