0

I have this multiple traits

trait router{

    function router_name(){
        return 'home';
    }

}

trait database{

    function database_name(){
        return 'app';
    }

}

trait httpinput{

    function input_name(){
        return 'get';
    }

}

and this array of names of traits

$cofig['traits'] = ['router','database','httpinput'];

and a class where all traits will be use in

class testclass{

}

now, how can I dynamically declare the traits inside the class using the $config array

I know I can do,

class testclass{
    use router,database,httpinput;
}

but I want to embed those traits dynamically base on those values on the $config array e.g.

foreach($config as $c){
    use $c;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164
  • This is not possible. – u_mulder Apr 07 '19 at 09:39
  • Similar question https://stackoverflow.com/questions/14355029/is-it-possible-to-add-traits-to-a-class-in-php-in-runtime – u_mulder Apr 07 '19 at 09:43
  • 3
    Defining classes gives your code predictable structure. Why does this have to happen dynamically? – deceze Apr 07 '19 at 09:46
  • 2
    If you, somehow, _would_ be able to make this work, you're setting yourself up for problems. If classes automatically change their definitions/API's, you won't be able to just look at a class to see what the API looks like. It will be a massive pain to debug and document your classes. – M. Eriksson Apr 07 '19 at 09:56
  • @deceze because traits by time will be added and removed, they store on a single and then I just include them – Juliver Galleto Apr 07 '19 at 09:58
  • @MagnusEriksson just that one class will be used, no other classes – Juliver Galleto Apr 07 '19 at 09:58
  • If only one class would have this, it would be even worse, since it would break consistency. Also, _why_ do you need this? It kind of sounds like a [XY-problem](http://xyproblem.info/). – M. Eriksson Apr 07 '19 at 09:59
  • I want those trait available only from that class to my application – Juliver Galleto Apr 07 '19 at 10:02
  • If the method declarions are dynamic, why not implement `__call` method? – shingo Apr 07 '19 at 10:07
  • 2
    How often do you add and remove traits that you need to dynamically figure them out *at runtime*…? I really think you’re trying to solve a non-issue here. – deceze Apr 07 '19 at 10:11
  • 1
    _"I want those trait available only from that class to my application"_ - Then why use traits? Just add the methods directly to your class. Also, if you want that class to do different things in different situations, how would you even _use_ that class since you won't know what methods exists in it? You should use different classes instead. – M. Eriksson Apr 07 '19 at 10:23

0 Answers0