CodeGodie
CodeGodie

Reputation: 12132

PHP 7 Bool Type Hint Not Working

Im a bit stumped with a scalar Type Hint issue (which PHP7 should be able to handle). Basically, Im creating a method with the bool type hint to only allow booleans to be passed. However it fails and lets other types like strings passed. I believe in the past this worked for me. Take a look at the snippet as an example. The first dump results in false (which makes sense since 'test' is a string), the second dump results in true which does not make sense to me. I was hoping for a PHP error to trigger since the type is not a boolean. Any thoughts?

<?php
class Test{
    function something(bool $test){
       var_dump($test); // "Second dump"
    }
}

$value = 'test';
var_dump(is_bool($value)); // "First dump"
$test = new Test;
$test->something($value);

Results:

bool(false) 
bool(true)

Upvotes: 5

Views: 1458

Answers (3)

delboy1978uk
delboy1978uk

Reputation: 12355

The magic feature you are looking for is this one. Put it on the first line above your class!

declare(strict_types=1) ;

Now your code will look klike this:

<?php
declare(strict_types=1) ;

class Test{
    function something(bool $test){
       var_dump($test); // "Second dump"
    }
}

$value = 'test';
var_dump(is_bool($value)); // "First dump"
$test = new Test;
$test->something($value);

Now it will throw an error! http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict

See it working here: https://3v4l.org/eLS1T

One last point, you need to set this on a per file basis

Upvotes: 1

Blackbam
Blackbam

Reputation: 19366

The problem is that PHP has automatic conversion for primitives. They did not change this for a long time probably for philosophic reasons. This why previously primitive type hinting was forbidden in PHP: https://bugs.php.net/bug.php?id=29508

As PHP has automatic conversions you should do this in order to be sure:

class Test{
    function something($test){
       if(!is_bool($test)) {
            throw new InvalidArgumentException("Boolean expected.");
       }
    }
}

Edit: Read the following article on scalar type hinting in PHP 7 https://www.phpclasses.org/blog/post/269-PHP-7-Scalar-Type-Hinting-Finally-Approved.html

In PHP 7 it finally is possible to make a code containing primitive type checking work by adding

declare(strict_types=1); 

in the beginning of the file.

Upvotes: 1

ashnazg
ashnazg

Reputation: 6688

You must declare strict typing [1] in the file in order to force PHP to not do type coercion [2].

[1] -- http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict

[2] -- "By default, PHP will coerce values of the wrong type into the expected scalar type if possible."

php <?php declare(strict_types=1);

Upvotes: 5

Related Questions