トレイトでプロパティの定義

概要

トレイトでプロパティを定義可能、しかしトレイトで参照することは困難と思われる


サンプル

ソース

<?php
	/********************************
	 * トレイトの確認
	 ********************************/
 
	// トレイトの定義
	trait TestTrait01{
 
		// プロパティ定義
		public $a = 10;
		public $b = 100;
 
		// トレイト内部でメソッドの定義
		public static function test01(){
			echo "TestTrait01::traitTest1 ";
		}
 
	}
 
	// クラスの定義
	class TestClass01{
		use TestTrait01;
 
		public function test02(){
			echo $this->a;
		}
		public function test03(){
			echo $this->b;
		}
	}
 
	/*******************************
	 * クラスを生成して実行
	 *******************************/
	$obj = new TestClass01();
	$obj->test01();
	echo "\n";
 
	$obj->test02();
	echo "\n";
 
	$obj->test03();
	echo "\n";
 
 

結果

>php -f sample12.php
TestTrait01::traitTest1
10
100
 
>
 


最終更新:2012年11月24日 23:59