【发布时间】:2012-11-25 04:07:03
【问题描述】:
有什么方法可以在 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" 用于string,"int" 用于int 等等,但这似乎很愚蠢。
【问题讨论】:
-
我不知道。不过有趣的问题。我只会传递 string 或 int (一些要打开的标识符)类型,即使它看起来“愚蠢”它不像 php 中常用的数百万种数据类型。
-
我认为你不能只使用 int、string 等。我认为这些是保留关键字,但不要引用我的话。甚至 gettype() 函数(我将用于这样的事情),以字符串格式返回类型:php.net/manual/en/function.gettype.php
-
gettype 只有在他想将传递的 var 转换为自己的类型时才有用。在这种情况下,他想将类型传递给 AS,与 $SomeOtherPara 不同。
标签: php types parameters