Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to add traits to a class in PHP in runtime?

Tags:

php

traits

Simple question, is it possible to dynamically add traits to a php class in runtime without using eval?

like image 220
Thomas Lauria Avatar asked Jan 16 '13 09:01

Thomas Lauria


People also ask

Can we instantiate Trait in PHP?

It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Can we use multiple traits in PHP?

PHP doesn't support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of classes, we can implement it.

What is difference between Trait and class in PHP?

The main difference between the Traits and Interfaces in PHP is that the Traits define the actual implementation of each method within each class, so many classes implement the same interface but having different behavior, while traits are just chunks of code injected in a class in PHP.

Can a Trait have a constructor PHP?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.


1 Answers

As Glavic said, you can't without using eval() or reflection hacks (and I'm not even sure about that).

But it's very unlikely you really need to.

You can achieve a lot with dynamic class composition (composing a class with some functionality you want into another class). That's simply a matter of putting a reference to the class with the desired functionality into a variable in the hosting class.

class SomeClassWithNeededFunctionality {}

class SomeClassThatNeedsTheFunctionalityOfTheOtherClass {
    private $serviceClass = NULL;

    public function __construct (SomeClassWithNeededFunctionality $serviceClass) {
        $this -> serviceClass = $serviceClass;
    }
}
like image 54
GordonM Avatar answered Sep 20 '22 15:09

GordonM