在 PHP 中有条件地使用特征


Use a trait conditionally in PHP

我想在类中使用特征,只有在满足条件的情况下。例如:

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

我知道我不能在课堂上直接使用if。因此,我正在寻找一种有条件地使用与上述相似的特征的方法。可能吗?

您可以使用 T 创建一个类,该类

在不使用 T 的情况下扩展该类。然后在使用该类的代码中执行 if 并实例化一个或另一个类。

<?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 */

你可以在一个特质中外包你的条件代码(如调试函数),然后做类似的事情。

//your Trait
if($isModeDbg){
    trait Dbg{
        function dbg(mssg){
            debugbarOrSomethingSimilar(mssg);
        }
    }
}else{
    trait Dbg{
        function dbg(mssg){
        }
    }
}
//your class
class Something{
  use Dbg;
}

只要可以在类根目录上评估您的条件,就可以执行以下操作:

if (<condition here>) {
    class BaseFoo
    {
        use FooTrait;
    }
} else {
    class BaseFoo {
    }
}
class Foo extends BaseFoo
{
    // common properties
}
trait T {
function getType() { 
     if($condition){ /*somthing*/ 
          }else{ 
           throw new Exception('some thing.') 
        } }
function getDescription() { /*2*/ }
}
class A {
use T;
/* ... */
}