Home >Backend Development >PHP Tutorial > 请教有没有人用过traits类型?有个有关问题需要问

请教有没有人用过traits类型?有个有关问题需要问

WBOY
WBOYOriginal
2016-06-13 12:54:37845browse

请问有没有人用过traits类型?有个问题需要问

<br />
<?php<br />
	trait Counter {<br />
		static $a = 5;<br />
		public function inc() {<br />
			static $c = 0;<br />
			$c += 1;<br />
			echo "$c<br />";<br />
		}<br />
	}<br />
	<br />
	class C1 {<br />
		use Counter;<br />
	}<br />
	<br />
	class C2 {<br />
		use Counter;<br />
	}<br />
	<br />
	<br />
	<br />
	$o = new C1();<br />
	$o->inc();<br />
	echo Counter::$a;<br />
	echo '<br />';<br />
	<br />
	$p = new C2();<br />
	$p->inc();<br />
?><br />


手册上讲“静态变量可以被 trait 的方法引用,但不能被 trait 定义。但是 traits 能够为使用的类定义静态方法”,但为什么我这个例子中的static $a = 5;又可以成功定义并最后成功输出?

class function php
------解决方案--------------------
trait 是 php 5.4 才加入的
你的手册是最新的吗?
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn