PHP的學習--Traits新特性

在閱讀yii2源碼的時候接觸到了trait,就學習了一下,寫下博客記錄一下。php

自 PHP 5.4.0 起,PHP 實現了代碼複用的一個方法,稱爲 traits。yii2

Traits 是一種爲相似 PHP 的單繼承語言而準備的代碼複用機制。Trait 爲了減小單繼承語言的限制,使開發人員可以自由地在不一樣層次結構內獨立的類中複用方法集。Traits 和類組合的語義是定義了一種方式來減小複雜性,避免傳統多繼承和混入類(Mixin)相關的典型問題。yii

Trait 和一個類類似,但僅僅旨在用細粒度和一致的方式來組合功能。Trait 不能經過它自身來實例化。它爲傳統繼承增長了水平特性的組合;也就是說,應用類的成員不須要繼承。學習

Trait 示例this

<?php
trait ezcReflectionReturnInfo {
    function getReturnType() { /*1*/ }
    function getReturnDescription() { /*2*/ }
}

class ezcReflectionMethod extends ReflectionMethod {
    use ezcReflectionReturnInfo;
    /* ... */
}

class ezcReflectionFunction extends ReflectionFunction {
    use ezcReflectionReturnInfo;
    /* ... */
}
?>

優先級

從基類繼承的成員被 trait 插入的成員所覆蓋。優先順序是來自當前類的成員覆蓋了 trait 的方法,而 trait 則覆蓋了被繼承的方法。spa

優先順序示例code

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

以上例程會輸出:Hello World!blog

從基類繼承的成員被插入的 SayWorld Trait 中的 sayHello 方法所覆蓋。其行爲 MyHelloWorld 類中定義的方法一致。優先順序是當前類中的方法會覆蓋 trait 方法,而 trait 方法又覆蓋了基類中的方法。繼承

另外一個優先級順序的例子ip

<?php
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class TheWorldIsNotEnough {
    use HelloWorld;
    public function sayHello() {
        echo 'Hello Universe!';
    }
}

$o = new TheWorldIsNotEnough();
$o->sayHello();
?>

以上例程會輸出:Hello Universe!

多個 trait

經過逗號分隔,在 use 聲明列出多個 trait,能夠都插入到一個類中。

多個 trait 的用法的例子

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World';
    }
}

class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

以上例程會輸出:Hello World!

衝突的解決

若是兩個 trait 都插入了一個同名的方法,若是沒有明確解決衝突將會產生一個致命錯誤。

爲了解決多個 trait 在同一個類中的命名衝突,須要使用 insteadof 操做符來明確指定使用衝突方法中的哪個。

以上方式僅容許排除掉其它方法,as 操做符能夠將其中一個衝突的方法以另外一個名稱來引入。

衝突解決的例子

<?php
trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}

class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}
?>

在本例中 Talker 使用了 trait A 和 B。因爲 A 和 B 有衝突的方法,其定義了使用 trait B 中的 smallTalk 以及 trait A 中的 bigTalk。

Aliased_Talker 使用了 as 操做符來定義了 talk 來做爲 B 的 bigTalk 的別名。

修改方法的訪問控制

使用 as 語法還能夠用來調整方法的訪問控制。

修改方法的訪問控制的例子

<?php
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

// 修改 sayHello 的訪問控制
class MyClass1 {
    use HelloWorld { sayHello as protected; }
}

// 給方法一個改變了訪問控制的別名
// 原版 sayHello 的訪問控制則沒有發生變化
class MyClass2 {
    use HelloWorld { sayHello as private myPrivateHello; }
}
?>

從 trait 來組成 trait

正如類可以使用 trait 同樣,其它 trait 也可以使用 trait。在 trait 定義時經過使用一個或多個 trait,它可以組合其它 trait 中的部分或所有成員。

從 trait 來組成 trait的例子

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World!';
    }
}

trait HelloWorld {
    use Hello, World;
}

class MyHelloWorld {
    use HelloWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>

以上例程會輸出:Hello World!

Trait 的抽象成員

爲了對使用的類施增強制要求,trait 支持抽象方法的使用。

表示經過抽象方法來進行強制要求的例子

<?php
trait Hello {
    public function sayHelloWorld() {
        echo 'Hello'.$this->getWorld();
    }
    abstract public function getWorld();
}

class MyHelloWorld {
    private $world;
    use Hello;
    public function getWorld() {
        return $this->world;
    }
    public function setWorld($val) {
        $this->world = $val;
    }
}
?>

Trait 的靜態成員

Traits 能夠被靜態成員靜態方法定義。

靜態變量的例子

<?php
trait Counter {
    public function inc() {
        static $c = 0;
        $c = $c + 1;
        echo "$c\n";
    }
}

class C1 {
    use Counter;
}

class C2 {
    use Counter;
}

$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

靜態方法的例子

<?php
trait StaticExample {
    public static function doSomething() {
        return 'Doing something';
    }
}

class Example {
    use StaticExample;
}

Example::doSomething();
?>

靜態變量和靜態方法的例子

<?php
trait Counter {
    public static $c = 0;
    public static function inc() {
        self::$c = self::$c + 1;
        echo self::$c . "\n";
    }
}

class C1 {
    use Counter;
}

class C2 {
    use Counter;
}

C1::inc(); // echo 1
C2::inc(); // echo 1
?>

屬性

Trait 一樣能夠定義屬性。

定義屬性的例子

<?php
trait PropertiesTrait {
    public $x = 1;
}

class PropertiesExample {
    use PropertiesTrait;
}

$example = new PropertiesExample;
$example->x;
?>

若是 trait 定義了一個屬性,那類將不能定義一樣名稱的屬性,不然會產生一個錯誤。若是該屬性在類中的定義與在 trait 中的定義兼容(一樣的可見性和初始值)則錯誤的級別是 E_STRICT,不然是一個致命錯誤。

衝突的例子

<?php
trait PropertiesTrait {
    public $same = true;
    public $different = false;
}

class PropertiesExample {
    use PropertiesTrait;
    public $same = true; // Strict Standards
    public $different = true; // 致命錯誤
}
?>

Use的不一樣

不一樣use的例子

<?php
namespace Foo\Bar;
use Foo\Test;  // means \Foo\Test - the initial \ is optional
?>

<?php
namespace Foo\Bar;
class SomeClass {
    use Foo\Test;   // means \Foo\Bar\Foo\Test
}
?>

第一個use是用於 namespace 的 use Foo\Test,找到的是 \Foo\Test,第二個 use 是使用一個trait,找到的是\Foo\Bar\Foo\Test。

__CLASS__和__TRAIT__

__CLASS__ 返回 use trait 的 class name,__TRAIT__返回 trait name

示例以下

<?php
trait TestTrait {
    public function testMethod() {
        echo "Class: " . __CLASS__ . PHP_EOL;
        echo "Trait: " . __TRAIT__ . PHP_EOL;
    }
}

class BaseClass {
    use TestTrait;
}

class TestClass extends BaseClass {

}

$t = new TestClass();
$t->testMethod();

//Class: BaseClass
//Trait: TestTrait

Trait單例

實例以下

<?php

trait singleton {    
    /**
     * private construct, generally defined by using class
     */
    //private function __construct() {}
    
    public static function getInstance() {
        static $_instance = NULL;
        $class = __CLASS__;
        return $_instance ?: $_instance = new $class;
    }
    
    public function __clone() {
        trigger_error('Cloning '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }
    
    public function __wakeup() {
        trigger_error('Unserializing '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }
}

/**
* Example Usage
*/

class foo {
    use singleton;
    
    private function __construct() {
        $this->name = 'foo';
    }
}

class bar {
    use singleton;
    
    private function __construct() {
        $this->name = 'bar';
    }
}

$foo = foo::getInstance();
echo $foo->name;

$bar = bar::getInstance();
echo $bar->name;

調用trait方法

雖然不很明顯,可是若是Trait的方法能夠被定義爲在普通類的靜態方法,就能夠被調用

實例以下

<?php 
trait Foo { 
    public static function bar() { 
        return 'baz'; 
    } 
} 

echo Foo::bar(),"\\n"; 
?>
相關文章
相關標籤/搜索