Answer the question
In order to leave comments, you need to log in
How to dynamically connect properties and methods of another class or trait to a class?
Good day to all. Is it possible to somehow dynamically link one class to another? There can be several base/parent classes, many plug-in/child classes/traits are assumed. In the parent class, the main logic and basic properties are defined, as well as the name of the included / child trait / class. In the included/child trait/class, there are additional properties and several methods that change the behavior of the parent class. So, is there any way in the base class to connect a trait or another class so that its properties and methods are available from the base / parent class?
class Object {
__construct($name) {
use $name;
//это вызовет ошибку, нужен какой-то аналог
}
}
trait Name {
public $x = 1;
public function metod() {
return 2;
}
}
$object = new Object('Name');
echo $object->x;
echo $object->metod();
//Что-то вроде такого...
Name extends $object_name
Answer the question
In order to leave comments, you need to log in
we make a class from Name, inject its instance into Object and add the __get and __call methods. But this is nonsense, it is better to think about architecture.
class Object
{
protected $di;
public function __construct($di)
{
$this->di = $di;
}
public function __get(string $name)
{
if (property_exists($this->di, $name)) {
return $this->di->$name;
} else {
throw new \Exception('бла бла');
}
}
public function __call(string $name, array $arguments)
{
if (method_exists($this->di, $name)) {
return $arguments ? $this->di->$name($arguments) : $this->di->$name();
} else {
throw new \Exception('бла бла');
}
}
}
class Name {
public $x = 1;
public function metod() {
return 2;
}
}
$object = new Object(new Name());
echo $object->x;
echo $object->metod();
How to dynamically connect properties and methods of another class or trait?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question