PHPの関数パラメーターにプリミティブデータ型を渡す(または同等に変数に格納する)方法はありますか?プリミティブ型とは、、、、などを意味int
します。bool
double
string
具体的には、次のようなことをしたいと思います。
function SomeFunc($DataType, $SomeOtherPara)
{
}
SomeFunc(int, "test1");
SomeFunc(bool, "test2");
考えられる使用法は次のとおりです。
//! Cast the input parameter into a data type, recursively.
/*!
\param[in] $DataType Data type, e.g. int, double, bool, string.
\param[in] $InputPara Any input parameter.
*/
function TypeJuggleRecursive($DataType, $InputPara)
{
if(is_array($InputPara))
{
// Work on each array element recursively.
$ReturnPara = array();
foreach($InputPara as $Key => $Value)
{
$ReturnPara[$Key] = TypeJuggleRecursive($DataType, $Value);
}
return $ReturnPara;
}
else
{
// Cast to data type.
return ($DataType)$InputPara;
}
}
TypeJuggleRecursive(bool, $_GET);
TypeJuggleRecursive(int, $_POST);
明らかな回避策は、代わりに文字列を使用することです。つまり"string"
、for string
、"int"
forint
などですが、それはばかげているようです。