2

PHPの関数パラメーターにプリミティブデータ型を渡す(または同等に変数に格納する)方法はありますか?プリミティブ型とは、、、、などを意味intします。booldoublestring

具体的には、次のようなことをしたいと思います。

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などですが、それはばかげているようです。

4

2 に答える 2

2

それを行うのが馬鹿げた方法だったとしたら、settype()が文字列を使用するとは思わない:)

http://php.net/manual/en/function.settype.php

于 2012-12-07T01:02:48.627 に答える
1

プリミティブデータ型は9つだけです。あなたが使用することができますgettype

function my_cast($value, $new_type) {
    switch(gettype($value)) {
        case 'boolean':
        case 'integer':
        case 'double':
        case 'string':
            // do something
            break;
        case 'array':
        case 'object':
        case 'resource':
            // do something else
            break;
        case 'NULL':
        default:
            // 'unknown type'
    }
}

PHPで実際に型を渡すことはできません。

于 2012-12-07T01:05:48.603 に答える