PHP 5.4 的 Trait 特性
Trait 是 PHP5.4 中的新特性,是 PHP 多重继承的一种解决方案。例如,需要同时继承两个 Abstract Class, 这将会是件很麻烦的事情,Trait 就是为了解决这个问题。
简单使用首先,当然是声明个 Trait,PHP5.4 增加了 trait 关键字:
trait first_trait { function first_method() { /* Code Here */ } function second_method() { /* Code Here */ }}
同时,如果要在 Class 中使用该 Trait,那么使用 use 关键字:
class first_class { // 注意这行,声明使用 first_trait use first_trait;}$obj = new first_class();// Executing the method from trait$obj->first_method(); // valid$obj->second_method(); // valid
在同个 Class 中可以使用多个 Trait:
trait first_trait{ function first_method() { echo "method1"; }}trait second_trait { function second_method() { echo "method2"; }}class first_class { // now using more than one trait use first_trait, second_trait;}$obj= new first_class();// Valid$obj->first_method(); // Print : method1// Valid$obj->second_method(); // Print : method2
同时,Trait 之间也可以相互的嵌套,例如:
trait first_trait { function first_method() { echo "method1"; }}trait second_trait { use first_trait; function second_method() { echo "method2"; }}class first_class { // now using use second_trait;}$obj= new first_class();// Valid$obj->first_method(); // Print : method1// Valid$obj->second_method(); // Print : method2
我们可以在 Trait 中声明需要实现的抽象方法,这样能使使用它的 Class 必须实现它:
trait first_trait { function first_method() { echo "method1"; } // 这里可以加入修饰符,说明调用类必须实现它 abstract public function second_method();}class first_method { use first_trait; function second_method() { /* Code Here */ }}
多个 Trait 之间同时使用难免会冲突,这需要我们去解决。PHP5.4 从语法方面带入了相关 的关键字语法:insteadof 以及 as ,用法参见:
trait first_trait { function first_function() { echo "From First Trait"; }}trait second_trait { // 这里的名称和 first_trait 一样,会有冲突 function first_function() { echo "From Second Trait"; }}class first_class { use first_trait, second_trait { // 在这里声明使用 first_trait 的 first_function 替换 // second_trait 中声明的 first_trait::first_function insteadof second_trait; }} $obj = new first_class();// Output: From First Trait$obj->first_function();
上面就是些 Trait 比较基本的使用了,更详细的可以参考官方手册。这里总结下注意的几 点:
Trait 会覆盖调用类继承的父类方法 Trait 无法如 Class 一样使用 new 实例化 单个 Trait 可由多个 Trait 组成 在单个 Class 中,可以使用多个 Trait Trait 支持修饰词(modifiers),例如 final、static、abstract 我们能使用 insteadof 以及 as 操作符解决 Trait 之间的冲突
坦白讲,我第一眼看到 Trait 对它并没有任何好感。PHP5 以来带来的新特性已经足够得 多,而且让开发者们有点应接不暇。
同时,Trait 更像是程序员的“语法糖”,然而它提供便利的同时可能会造成巨大的隐患。 例如 Trait 能够调用类中的成员:
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 没有效果:
trait HelloWorld { public function sayHello() { echo 'Hello World!'; }}class TheWorldIsNotEnough { use HelloWorld; public function sayHello() { echo 'Hello Universe!'; }}$o = new TheWorldIsNotEnough();$o->sayHello(); // echos Hello Universe!
那么 Trait 的出现是为何呢?有哥们的回答比较有意思,但不无道理:
因为php没有javascript作用域链的机制,所以无法把function bind到class里面,曾经以为php 5.3的闭包可以做这个事,最后才发觉作用域的设计不允许这么干
但话说回来,拿 interface 和 Trait 类比,显然 Trait 有更多方便的地方(虽然 两者不能完全相互替代)。
不过很显然 Trait 目前还处于测试阶段,它的未来相比其他 PHP5 新推来的特性还有 更多让人观望的地方,但或许这特性能改变 PHP5 未来继承的方式。
因为,我个人坚信 PHP 的作用链设计迟早会改得“更像 JavaScript”,即便这事情会在遥远的 PHP6 。
参考链接 http://php.net/manual/en/language.oop5.traits.php https://wiki.php.net/rfc/traits http://en.wikipedia.org/wiki/Trait_%28computer_programming%29 http://bbs.phpchina.com/thread-210870-1-1.html http://scg.unibe.ch/research/traits/ http://walu.sinaapp.com/?p=60 http://www.phppan.com/2011/07/mixin-and-trait/转自: http://www.kuqin.com/web/20111119/315048.html

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> 'Hello World', 'github.com'=> [ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다
