アットウィキロゴ

タイプヒンティング

概要

関数やクラスのメソッドを使用する場合にクラス名を定義することで受け取るデータを制限することが可能


サンプル

ソース

<?php
// エラーを例外に変換
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
 
/*******************************
 * タイプヒンティング
 *******************************/
class TestClass01{
	public function test01(TestClass02 $obj){
		echo __METHOD__ . "\n";
	}
}
class TestClass02{
	public function test01(){
		echo __METHOD__ . "\n";
	}
}
 
/*******************************
 * テスト
 *******************************/
$obj1 = new TestClass01();
$obj2 = new TestClass02();
 
// TestClass02のインスタンスを指定
$obj1->test01($obj2);	// 正常
 
// stdClassを指定
try{
	$o = new StdClass();
	$obj1->test01($o);
}catch(Exception $e){
	echo $e->getMessage() . "\n";
}
 
// スカラー変数を指定
try{
	$o = "11111";
	$obj1->test01($o);
}catch(Exception $e){
	echo $e->getMessage() . "\n";
}
 
 

結果

D:\Tools\xampp\htdocs\sample>php -f sample01.php
TestClass01::test01
Argument 1 passed to TestClass01::test01() must be an instance of TestClass02, instance of stdClass given, called in D:\Tools\xampp\htdocs\sample\sample01.php on line 34 and defined
Argument 1 passed to TestClass01::test01() must be an instance of TestClass02, string given, called in D:\Tools\xampp\htdocs\sample\sample01.php on line 42 and defined
 
D:\Tools\xampp\htdocs\sample>
 



最終更新:2012年11月25日 14:14