php: Declare arguments type of a Function
According to the PHP5 documentation:
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
Since string
and int
are not classes, you can't "type-hint" them in your function.
As of PHP 7.0 declaring argument type as string, int, float, bool is supported.
This maybe useful for anyone who see this post since the availability of PHP 7
With PHP 7, its now possible to declare types. You can refer the following link for more information.
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
function(string $name, boolean $is_admin) { //do something}
You can do something like this which has always worked for me
for string
function setData($Name=""){ }
this forces the name to be a string, it doesn't check if its a string
for numeric values
function setData($age=0){ }
this forces the age to be a number, if a string is passed, the value will be 0
for array values , there are two variation
function setData(array $data){ }
if an array is not passed, it would throw an error
function setData($data=array()){ }
This would pass an empty array of no value is given for $data