W
W
wadowad2017-09-29 12:06:51
PHP
wadowad, 2017-09-29 12:06:51

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();

Or maybe there is some way to go the other way and set the name of the parent class dynamically?
//Что-то вроде такого...
Name extends $object_name

I guess I'm trying to reinvent the wheel and there are more logical ways.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SharuPoNemnogu, 2017-09-29
@wadowad

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();

M
Maxim Fedorov, 2017-09-29
@qonand

How to dynamically connect properties and methods of another class or trait?

By means of the language, in no way, and changing the behavior / structure of an object is a bad practice that violates the substitution principle of Barbara Liskov. I don’t fully understand your task, but I would recommend looking towards aggregation and composition

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question