0

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?

3 Answers 3

1

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.');
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Not impossible, just harder than you might think - nikic.github.com/2012/03/06/…
0

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...

1 Comment

And your function will be like generateFiles(getArray($var1), getBool($var2), getInt($var3)); for getArray, for example, you can do: if(is_array($var)) { return $var; } else { return array($var); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.