Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

Type hinting/casting request for vote

via. Type hinting for PHP 5.3 - iBlog - Ilia AlshanetskyType hinting rehashed (now with type casting support) - iBlog - Ilia Alshanetsky

コア開発者の1人であるIlia氏が、開発者メーリングリストにパッチを投げ、投票フェーズに入ったようです。


Last week or so there was a fairly detailed discussion on the internals list regarding type hinting based on my original patch. Since then the patch has been revised to address the major concerns that were identified (breakage of binary compatibility) as well extended with additional functionality (object hint, type casting, reflection support, etc...).

The final patch is available here: http://ilia.ws/patch/type_hint_53_v2.txt
The test suit is available here: http://ia.gd/patch/type_hint_tests.tar.bz2

I would like to ask all developers to voice their opinions of whether it makes sense to add this to 5.3 or to throw it away (either one is fine btw). To keep the process simple & flamewar free, please restrict yourself to +/- (1/0), next week monday I'll run a tally of the votes and based on the result we can determine how to proceed further.

Ilia氏としては、このパッチをPHP5.3.xに突っ込みたいみたいです。これに対する反応としては、"+1"というものが多いようですが、「PHP5.4とかPHP6なら良いよ」というのもそれなりにあるようです。まあ、どこでどんでん返しがあるか分かりませんが、このまま行くとパッチがマージされる可能性は高いんじゃないでしょうか。

で、このパッチでどう変わるのか?ですが、次のような感じです。

タイプヒンティング

クラス型やarray以外に"int"や"string"などが使えるようになります。個人的にはこれだけでも欲しい。というか、PHP5.3.1で良いから、とっととマージしてくれ。

<?php
function test(int $a, double $b, string $c, boolean $d = true, resource $e, array $f = array(), object $g) {
}

$func = new ReflectionFunction('test');
Reflection::Export($func);

foreach ($func->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n",
        $i, 
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),        
        $param->isOptional() ? 'yes' : 'no'
    );
    printf("   Int: %d | Double: %d | Bool: %d | String: %d | Resource: %d | Array: %d | Object: %d\n", 
    	$param->isInt(), $param->isDouble(), $param->isBool(), $param->isString(),
    	$param->isResource(), $param->isArray(), $param->isObject());
		print "}\n";
}

?>

タイプキャスト

引数に型宣言ではなくキャストを書くというもの。うーん。個人的には微妙だなぁ。(PHPの)キャストに依存したくないなぁ。。。

<?php

function test_string((string) $a = 'a') {
	var_dump($a);
}

test_string(1);
test_string('1211');
test_string(array(1));
test_string(false);

ちなみに

PHP5.3.0に上のパッチを当てることもできるようですが、タイプキャストの方しか動作しませんでした。。。残念。。。

追記(2009/07/09 17:50)

これは大どんでんが始まりか。。。?

追記2(2009/07/12 17:25)

このパッチはPHP5.3.0でもちゃんと適用でき、動作します。Type hinting/castingパッチはPHP5.3.0でも動く - Do You PHP はてなを参照してください。