Reputation: 1890
In some programming languages such as Java or C# it's allowed for programmer to set allowed input variable types. I use PHP and I want to do the same to avoid passing wrong data to my methods/functions.
My code:
public static function generateFiles(array $data, Custom_Pager $pager)
{...}
Why is that allowed and I cant write like that:
public static function generateFiles(array $data, Custom_Pager $pager, int $limit, string $text)
{ ... }
Is any way to standardize first and second method declarations I presented above? If no, why?
Upvotes: 0
Views: 74
Reputation: 674
I made a function to force type hinting. It works something like that:
function getVar($var,$type) {
switch($type) {
case "int":
return (int)$var;
case "string":
return (string)$var;
}
}
You can continue with all other types. Also you can make the same method to check variables for is_int, is_string, is_bool etc...
Upvotes: 0
Reputation: 6442
Yes, you can force the parameters to be of a certain type using type hinting, but it apparently does not work with primitive types.
You can, however, throw an exception in the method if the parameter values does not meet your expectations.
if (!is_int($param))
throw new Exception('param must be int.');
Upvotes: 1
Reputation: 22592
PHP is a weak-typed language, so that isn't possible.
PHP5.1 introduced Type Hinting, though it has it's limitations:
Type hints can not be used with scalar types such as int or string. Traits are not allowed either.
Upvotes: 1