3. Traits
Stefan Marr氏がinternalsに提案した
新たな構文
http://news.php.net/php.internals/35562
2008/02/18
Request for Comments: Traits for PHP
http://www.stefan-marr.de/artikel/rfc-traits-for-
php.html
3
4. <?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(); // echos Hello World!
?>
4
5. <?php
複数use
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();
// Results eventually in: Hello World!
5
6. <?php
trait Hello {
mix-in
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();
// Results eventually in: Hello World!
?>
6