As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
It is useful in single inheritance languages.
Trait is similar class, but only it make to group functionality.
For example, you need same functions in two absolutely different class.
At that time declare that functions as trait and use it in your class.
Like this..
<?php
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
?>
The getRetuntType and getReturnDescription functions not declared in ReflectionMethod and each classes.
This function declare in ezcReflectionReturnInfo trait.
You can use that two functions in your different kind classes.
This Trait make your code more reuseful.
You can use multi Trait and implementation under an additional alias to conflict resolution.
<?php
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
class Aliased_Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
B::bigTalk as talk;
}
}
?>
And also can changing method visibility.
class MyClass1 {
use HelloWorld { sayHello as protected; }
}
As 7.0.0, defining a property in the class with the same visibility and initial value as in the trait, no more E_STRICT notice.
You can set properties in trait and use it and redefine in your class.
'Develop > PHP' 카테고리의 다른 글
전화번호 국내 지역화 코드 (0) | 2018.10.23 |
---|---|
전화번호 체크하기(휴대전화, 유선, 대표번호 등등) (0) | 2018.10.23 |
Use JWT with public-key cryptography (0) | 2018.04.24 |
php_value 값 설정하기 (0) | 2018.02.02 |
가상화폐 실시간 가격정보 받아오는 방법 (4) | 2018.01.13 |