25

I'd like my functions to expect strings/integers or throw a fit, like:

warning: preg_match() expects parameter 2 to be string

However for this function

public function setImage($target, $source_path, integer $width, integer $height){...

I get:

Argument 4 passed to My_Helper_Image::setImage() must be an instance of integer, integer given

But:

function(array $expectsArray)

works as I expect, how would I achieve the same effect as with integers and strings?

Big Update

PHP 7 now supports Scalar Type Hinting

function increment(int $number) {
     return $number++;
}
1

4 Answers 4

26

Scalar TypeHints are available as of PHP 7:

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.

There is no Type Hints for scalars before PHP7. PHP 5.3.99 did have scalar typehints but it wasn't finalised at that point if they stay and how they will work then.

Nevertheless, there is options for enforcing scalar arguments before PHP7.

There is a couple of is_* functions that let you do that, e.g.

To raise a Warning, you'd use

with an E_USER_WARNING for $errorType.

Example

function setInteger($integer)
{
    if (FALSE === is_int($integer)) {
        trigger_error('setInteger expected Argument 1 to be Integer', E_USER_WARNING);
    }
    // do something with $integer
}

Alternative

If you want to use Scalar Type Hints desperately, have a look at

which shows a technique for enforcing scalar typehints via a custom Error Handler.

Sign up to request clarification or add additional context in comments.

Comments

7

You can use "Type Juggling" like (int)$height.

For example:

function setImage($target, $source_path, integer $width, $height) {
    $height = (int)$height;
    ...
}

Comments

3

PHP does not (yet) implement strong typing, therefore you cannot force a parameter to be an integer. It does only apply to classes (the error you get imply that $width should be an instance of class integer) and arrays.

Type hinting for classes is available in PHP 5, type hinting for arrays starting with 5.1, and apparently scalar type hinting may (or may not) be available in the future.

You can of course as others have pointed out, check for type within your function/method, but that is fundamentally different from strong typing. The desired effect will of course be present either way.

3 Comments

So the warnings thrown by php are checked withing the function?
Functions like preg_replace are not written in PHP and therefore does not have to abide to the rules of the PHP language. You would have to consult the source code to see that, but my gut feeling tells me that is the case.
It could also be a case where PHP (the runtime) internally checks this against the function declaration (since it is written in c, it has type defined for parameters) and then decides what to do. The function php_pcre_match_impl() clearly states that subject should be char *.
0

If you are not using PHP 7.x or you can use args module from Non-standard PHP library (NSPL). It is not as fancy and PHP 7.x type-hinting but does the validation:

use const \nspl\args\numeric;
use function \nspl\args\expects;

function sqr($x)
{
    expects(numeric, $x);
    return $x * $x;
}

sqr('hello world');

Outputs:

InvalidArgumentException: Argument 1 passed to sqr() must be numeric, string given in /path/to/example.php on line 17

Call Stack:
    0.0002     230304   1. {main}() /path/to/example.php:0
    0.0023     556800   2. sqr() /path/to/example.php:17

Comments

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.