<?php
trait T{
static function myDefault(){return "T::Default ";}
static public function myPublic(){return "T::Public ";}
static protected function myProtected(){return "T::Protected ";}
static private function myPrivate(){return "T::Private ";}
function testT1(){
echo T::myDefault();
echo T::myPublic();
//echo T::myProtected();//error,不解
//echo T::myPrivate();//error,不解
}
function testT2(){
echo self::myDefault();
echo self::myPublic();
echo self::myProtected();
echo self::myPrivate();
}
function testT3(){
echo $this::myDefault();
echo $this::myPublic();
echo $this::myProtected();
echo $this::myPrivate();
}
function testT4(){
echo static::myDefault();
echo static::myPublic();
echo static::myProtected();
echo static::myPrivate();
}
}
class A{
use T;
function testA1(){
echo T::myDefault();
echo T::myPublic();
//echo T::myProtected();//error,不解
//echo T::myPrivate();//error,不解
}
function testA2(){
echo A::myDefault();
echo A::myPublic();
echo A::myProtected();
echo A::myPrivate();
}
function testA3(){
echo self::myDefault();
echo self::myPublic();
echo self::myProtected();
echo self::myPrivate();
}
function testA4(){
echo $this::myDefault();
echo $this::myPublic();
echo $this::myProtected();
echo $this::myPrivate();
}
function testA5(){
echo static::myDefault();
echo static::myPublic();
echo static::myProtected();
echo static::myPrivate();
}
}
echo A::myDefault();
echo A::myPublic();
//echo A::myProtected();//error
//echo A::myPrivate();//error
$obj = new A;
echo $obj::myDefault();
echo $obj::myPublic();
//echo $obj::myProtected();//error
//echo $obj::myPrivate();//error
echo "<br/>";$obj->testT1();
echo "<br/>";$obj->testT2();
echo "<br/>";$obj->testT3();
echo "<br/>";$obj->testT4();
echo "<br/>";$obj->testA1();
echo "<br/>";$obj->testA2();
echo "<br/>";$obj->testA3();
echo "<br/>";$obj->testA4();
echo "<br/>";$obj->testA5();
?>
不要用
T
,用self
trait
是不能实例化的,可以理解为介于(?)interface
和abstract class
之间self