【问题标题】:Pass primitive data type into function parameter将原始数据类型传递给函数参数
【发布时间】:2012-11-25 04:07:03
【问题描述】:

有什么方法可以在 PHP 中将原始数据类型传递给函数参数(或等效地将其存储到变量中)?我所说的原始类型是指intbooldoublestring 等。

更具体地说,我想做这样的事情:

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" 用于string"int" 用于int 等等,但这似乎很愚蠢。

【问题讨论】:

  • 我不知道。不过有趣的问题。我只会传递 string 或 int (一些要打开的标识符)类型,即使它看起来“愚蠢”它不像 php 中常用的数百万种数据类型。
  • 我认为你不能只使用 int、string 等。我认为这些是保留关键字,但不要引用我的话。甚至 gettype() 函数(我将用于这样的事情),以字符串格式返回类型:php.net/manual/en/function.gettype.php
  • gettype 只有在他想将传递的 var 转换为自己的类型时才有用。在这种情况下,他想将类型传递给 AS,与 $SomeOtherPara 不同。

标签: php types parameters


【解决方案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 中实际传递类型。

【讨论】:

    【解决方案2】:

    如果这是一种愚蠢的做法,我认为 settype() 不会使用字符串 :)

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

    【讨论】:

    • 有道理,如果 PHP 和我一样笨,我会很高兴的。 :-P
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多