F
F
fsgdoterr2021-11-02 13:21:43
PHP
fsgdoterr, 2021-11-02 13:21:43

Why are traits needed in php?

While studying php, I came to the study of traits, having studied the documentation, and by googling I understood the essence of the use, but I still did not understand the essence of the application, because exactly the same result can be achieved by writing an abstract class and simply inheriting from it, I will give one of the examples that I found:

trait HelloWorld{    
    public function sayHello() {
        return 'Привет ';
    }
}
class NameMen{
    public $name = 'Вася';
}
class GetInfo extends NameMen{
    use HelloWorld;
    public function getPiple(){
            echo $this->sayHello() . $this->name;
    }
}
$obj = new GetInfo();
$obj->getPiple(); //Привет Вася

here is one of them, and all the others look about the same, I understood the essence of such examples, methods are declared in the trait that supposedly will need to be used many times, and in order not to prescribe them again and again, you declare them there, but as I wrote above that the same effect can be achieved by writing an abstract class and inheriting from it, so why do we need these traits, where is it better to use them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-11-02
@fsgdoterr

Traits are mixins that can be added to classes in various combinations. Try to repeat on pure classes

trait Harvestable {
  function harvest() { }
}
trait Waterable {
  function water() { }
}
trait Repottable {
  function repot() { }
};
class Plant { }
class Vegetable extends Plant {
  use Waterable;
  use Harvestable;
}
class Fruit extends Plant {
  use Waterable;
  use Harvestable;
  use Repottable;
}
class Succulent extends Plant {
  use Repottable;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question