17

I want to use a trait in a class, only if a condition is satisfied. For example:

trait T
{
}
class A
{
    if ($condition) {
        use T;
    }
}

I know I can't use if directly in class. So, I'm looking for a way to use traits conditionally similar to the above. Is it possible?

4

4 回答 4

15

You can create a class with use T which extends the class without use T. And then in your code where you use the class do an if and instantiate the one or the other class.

<?php

trait T {
}

class A {
}

class B extends A {
    use T;
}

// In an other part of code
$obj = null;

if($condition) {
    $obj = new B();
} else {
    $obj = new A();
}

/* EOF */
于 2013-11-05T06:56:40.567 回答
3

You can outsource your conditional code (like debug-functions) in a trait and do something like that.

//your Trait

if($isModeDbg){
    trait Dbg{
        function dbg(mssg){
            debugbarOrSomethingSimilar(mssg);
        }
    }
}else{
    trait Dbg{
        function dbg(mssg){
        }
    }
}

//your class
class Something{
  use Dbg;
}
于 2017-03-24T12:12:39.747 回答
3

As long as your condition can be evaluated at the class root, you can do the following:

if (<condition here>) {
    class BaseFoo
    {
        use FooTrait;
    }
} else {
    class BaseFoo {
    }
}

class Foo extends BaseFoo
{
    // common properties
}
于 2020-11-02T01:08:31.013 回答
1
trait T {
function getType() { 
     if($condition){ /*somthing*/ 
          }else{ 
           throw new Exception('some thing.') 
        } }
function getDescription() { /*2*/ }
}
class A {
use T;
/* ... */
}
于 2013-11-05T07:04:45.767 回答