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。
以上就是php trait 的静态成员、抽象成员、属性代码详解的详细内容。