Php 将基元数据类型传递到函数参数
有没有什么方法可以在PHP中将基本数据类型传递到函数参数中(或者等效地,将其存储到变量中)?基本类型指的是Php 将基元数据类型传递到函数参数,php,types,parameters,Php,Types,Parameters,有没有什么方法可以在PHP中将基本数据类型传递到函数参数中(或者等效地,将其存储到变量中)?基本类型指的是int,bool,double,string,等等 更具体地说,我想这样做: function SomeFunc($DataType, $SomeOtherPara) { } SomeFunc(int, "test1"); SomeFunc(bool, "test2"); 一种可能的用法可能是: //! Cast the input parameter into a data type,
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”
,int的“int”
,等等,但这似乎很愚蠢。如果这是一种愚蠢的方法,我不认为settype()会使用字符串:)
只有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中实际传递类型。据我所知,这是不可能的。不过这是个有趣的问题。我只会传递string或int(一些要打开的标识符)类型,即使它看起来很“愚蠢”。php中常用的数据类型并不是数以百万计。我不认为您可以只使用int、string等。我假设这些是保留关键字,但不要引用我的话。即使是gettype()函数(我会用它来处理类似的事情),也会以字符串格式返回类型:只有当他想将传递的变量转换为自己的类型时,gettype才有用。在本例中,他希望将类型传递给cast-AS,这与$SomeOtherPara不同。有道理,如果PHP和我一样愚蠢,我会很高兴的-P