Is there any way I can pass a primitive data type into a function parameter (or equivalently, store it into a variable) in PHP? By primitive types I mean int, bool, double, string, etc.
More specifically, I would like to do something like this:
function SomeFunc($DataType, $SomeOtherPara)
{
}
SomeFunc(int, "test1");
SomeFunc(bool, "test2");
A possible usage might be:
//! 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);
An obvious workaround would be to use strings instead, i.e. "string" for string, "int" for int, etc., but that seems dumb.
If it was a dumb way to do it, I don’t think settype() would use a string 🙂
http://php.net/manual/en/function.settype.php