Answer the question
In order to leave comments, you need to log in
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(); //Привет Вася
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question