Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "traditional" type-hinting not allowed in PHP?

Just discovered that type-hinting is allowed in PHP, but not for ints, strings, bools, or floats.

Why does PHP not allow type hinting for types like integer, strings, ... ?

like image 607
mpen Avatar asked Jan 21 '11 00:01

mpen


Video Answer


1 Answers

As of PHP 7.0 there is support for bool, int, float and string. Support was added in the scalar types RFC. There are two modes: weak and strict. I recommend reading the RFC to fully understand the differences, but essentially type conversions only happen in weak mode.

Given this code:

function mul2(int $x) {
    return $x * 2;
}
mul2("1");

Under weak mode (which is the default mode) this will convert "1" to 1.

To enable strict types add declare(strict_types=1); to the top of the file. Under strict mode an error will be emitted:

Fatal error: Argument 1 passed to mul2() must be of the type integer, string given

like image 144
Levi Morrison Avatar answered Oct 22 '22 21:10

Levi Morrison