在PHP中有条件地使用特征

Mou*_*uli 10 php traits

我想在类中使用特征,只有在条件满足时才使用.例如:

trait T
{
}
class A
{
    if ($condition) {
        use T;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我不能if直接在课堂上使用.所以,我正在寻找一种方法来使用与上述类似的特征.可能吗?

TiM*_*TER 10

你可以创建一个使用T的类,它不使用T扩展类.然后在你使用类的代码中执行if和instanciate一个或另一个类.

<?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 */
Run Code Online (Sandbox Code Playgroud)