Traits 是 PHP 5.4 之後推出的功能,用來做 Mixin 的多重繼承

在進行物件導向的開發時,會把一些可以reuse的方法抽出寫成另一個類別,要使用時再繼承該類別。但當這樣子的類別一多,可能就會遇到一個類別為了特定function而不斷繼承,此時 Traits 就可以派上用場。

範例
1.基本使用

trait sayAction {
    public $x = 3;
    function sayHello() {
        echo "Hello" . PHP_EOL;
    }

    function sayName($name) {
        echo "My name is ${name}" . PHP_EOL;
    }
}

class leagcy {
    //dosomething
}

class product extends leagcy {
    use sayAction;
}

$product = new product();
$product->sayHello();
$product->sayName('Johnson');
echo $product->x . PHP_EOL;

2.Parent

class leagcy {
    function sayHello() {
        echo 'Leagcy Hello' . PHP_EOL;
    }
}

trait sayAction {
    function sayHello() {
        parent::sayHello();
        echo "Hello" . PHP_EOL;
    }
}

class product extends leagcy {
    use sayAction;
}

$product = new product();
$product->sayHello();

3.同時使用多個 Trait

class leagcy {
    //dosomething
}

trait sayAction {
    function sayHello() {
        echo "Hello" . PHP_EOL;
    }
}

trait goAction {
    function goDie() {
        echo "Die" . PHP_EOL;
    }
}

class product extends leagcy {
    use sayAction,goAction;
}

$product = new product();
$product->sayHello();
$product->goDie();

4.利用Trait 繼承 Trait

class leagcy {
    //dosomething
}

trait sayAction {
    function sayHello() {
        echo "Hello" . PHP_EOL;
    }
}

trait goAction {
    function goDie() {
        echo "Die" . PHP_EOL;
    }
}

trait execAction {
    use sayAction,goAction;
}

class product extends leagcy {
    use execAction;
}

$product = new product();
$product->sayHello();
$product->goDie();

5.Abstract

class leagcy {
    //dosomething
}

trait sayAction {
    abstract public function sayHello();
}

class product extends leagcy {
    use sayAction;
    function sayHello() {
        echo "Hello" . PHP_EOL;
    }
}

$product = new product();
$product->sayHello();

6.Static

class leagcy {
    //dosomething
}

trait sayAction {
    function calCount() {
        static $count = 0;
        $count++;
        echo $count . PHP_EOL;
    }

    static function staticFnc() {
        echo "Static" . PHP_EOL;
    }
}

class product extends leagcy {
    use sayAction;
}

class other {
    use sayAction;
}

product::staticFnc();
$product1 = new product();
$product2 = new product();
$product1->calCount();
$product2->calCount();

$other = new other();
$other->calCount();
Categories: PHP