PHP 5.4 的 Trait 特性

Posted by hiho on July 20, 2014

  Trait 是 PHP5.4 中的新特性,是 PHP 多重继承的一种解决方案。例如,需要同时继承两个 Abstract Class, 这将会是件很麻烦的事情,Trait 就是为了解决这个问题。

简单使用

首先,当然是声明个 Trait,PHP5.4 增加了 trait 关键字

/**
 * 定义第一个trait
 */
trait first_trait 
{
    /**
     * 第一个trait的方法一
     */
    function first_method() 
    { 
        /* Code Here */
         echo 'first';
    }
    
    /**
     * 第一个trait的方法二
     */
    function second_method1() 
    { 
        /* Code Here */
         echo 'second';
    }
}

同时,如果要在 Class 中使用该 Trait,那么使用 use 关键字


class first_class 
{
    // 注意这行,声明使用 first_trait
    use first_trait;
}

$obj = new first_class();

// Executing the method from trait
$obj->first_method(); //结果输出:first
$obj->second_method(); // 结果输出:second

使用多个Trait

在同个 Class 中可以使用多个 Trait

trait first_trait
{
    function first_method() 
    { 
        echo "first"; 
    }
}

trait second_trait 
{
    function second_method() 
    { 
        echo "second"; 
    }
}

class first_class 
{
    // now using more than one trait
    use first_trait, second_trait;
}

$obj= new first_class();
$obj->first_method(); // Print : first
$obj->second_method(); // Print : second

Trait 之间的嵌套

同时,Trait 之间也可以相互的嵌套,例如


trait first_trait 
{
    function first_method() 
    { 
        echo "first"; 
    }
}

trait second_trait 
{
    use first_trait;
    function second_method() 
    { 
        echo "second"; 
    }
}

class first_class {
    // now using 
    use second_trait;
}

$obj= new first_class();
$obj->first_method(); // Print : first
$obj->second_method(); // Print : second

Trait 的抽象方法(Abstract Method)

我们可以在 Trait 中声明需要实现的抽象方法,这样能使使用它的 Class 必须实现它

trait first_trait 
{
    function first_method() 
    { 
        echo "first"; 
    }

    // 这里可以加入修饰符,说明调用类必须实现它
    abstract public function second_method();
}

class first_method {
    use first_trait;

    function second_method() 
    {
        /* Code Here */
    }
}

Trait 冲突

多个 Trait 之间同时使用难免会冲突,这需要我们去解决。PHP5.4 从语法方面带入了相关 的关键字语法:insteadof 以及 as ,用法参见

rait first_trait 
{
    function first_function() 
    { 
        echo "first";
    }
}

trait second_trait {
    // 这里的名称和 first_trait 一样,会有冲突
    function first_function() 
    { 
        echo "second";
    }
}

class first_class {
    use first_trait, second_trait 
    {
        // 在这里声明使用 first_trait 的 first_function 替换 second_trait 中first_function的声明
        first_trait::first_function insteadof second_trait;
    }
}  

$obj = new first_class();
$obj->first_function();//print first

需要注意的几点

上面就是些 Trait 比较基本的使用了,更详细的可以参考官方手册。这里总结下注意的几 点:

  • Trait 会覆盖调用类继承的父类方法
  • Trait 无法如 Class 一样使用 new 实例化
  • 单个 Trait 可由多个 Trait 组成
  • 在单个 Class 中,可以使用多个 Trait
  • Trait 支持修饰词(modifiers),例如 final、static、abstract
  • 我们能使用 insteadof 以及 as 操作符解决 Trait 之间的冲突
  • 类中实现方法会覆盖Trait的同名方法

—End—

迭代

  • 2014年7月20日 13:04:17 初稿