3 ms·
Can somebody explain this to a non-phper? So PHP got strict types, but only for Scalars (Ints and floats) and they can be enabled on a per-file basis. Right?
by 1ris 12y ago
Can somebody explain this to a non-phper? So PHP got strict types, but only for Scalars (Ints and floats) and they can be enabled on a per-file basis. Right?
- TazeTSchnitzel 12y agoPHP has had type hints for classes for more than a decade now: function foobar(MyClass $foo) { // do stuff } foobar(new NotMyClass()); // throws an error This just adds type hints for the scalar types (integer, float, string and boolean). Since PHP has a long tradition of weak typing and this is what PHP's built-in and extension functions use, weak is the default behaviour, allowing some conversions: function foo(int $x) { var_dump($x); } foo("12"); // produces int(12) foo(null); // throws an error But, you can optionally turn on a strict type-checking mode for scalars on a per-file basis, which doesn't allow conversions: <?php declare(strict_types=1); function foo(int $x) { var_dump($x); } foo("12"); // throws an error foo(null); // throws an error
- deleted 12y ago[deleted]
- Danack 12y agoPHP has had type-hints for parameters for several version, but they could only be used for classes. The new types-hints cover the 'scalar' values (aka not object) and are int, float, string and bool. They allow a function to declare what they types of the variables it receives should be like: function foo(int $x) { // x is guaranteed to be an int. } The type-hinting for scalars has two modes: * strict - the parameter passed to the function must be of the exact* type. * weak - the parameter passed to the function will be converted to the correct type. The strictness depends on what mode PHP was in when the function was called. This is the right choice as it: * Allows library authors to write their code in either strict or weak mode. * End-users to write their code in either strict or weak mode. Or even without using scalar type-hints. * End-user to be able to choose when they are writing their code do they want their variables to be converted to the type expected by the library automatically, or do they want PHP to give them an error if they accidentally pass the wrong type of variable to a function that is expecting an int. *except for some widening rules, e.g. you can pass an int where a float is expected, as ints can be converted into float without data loss (for ints less than 2^53).
- johnny22 12y agothey could have been interfaces, or arrays too.