Scalar Type Hints
Posted by PHPVote 8 years ago
Hey !
What do you think about the "Scalar Type Hints" RFC ?
I love the idea to be able to have both possibility.
```php
class ElePHPant {
public $name, $age, $cuteness, $evil;
public function __construct(string $name, int $age, float $cuteness, bool $evil) {
$this->name = $name;
$this->age = $age;
$this->cuteness = $cuteness;
$this->evil = $evil;
}
}
```
First :
```php
$sara = new ElePHPant("Sara", 7, 0.99, FALSE);
var_dump($sara); /*
object(ElePHPant)#1 (4) {
["name"]=>
string(4) "Sara"
["age"]=>
int(7)
["cuteness"]=>
float(0.99)
["evil"]=>
bool(false)
} */
// But it will also work with normal casting like that you are sure to received int, string, ... :
$nelly = new ElePHPant(12345, "7 years", "0.9", "1");
var_dump($nelly); /*
object(ElePHPant)#2 (4) {
["name"]=>
string(5) "12345"
["age"]=>
int(7)
["cuteness"]=>
float(0.9)
["evil"]=>
bool(true)
}
Notice: A non well formed numeric value encountered
*/
```
Second :
```php
declare(strict_types=1);
$nelly = new ElePHPant(12345, "7 years", "0.9", "1");
// Catchable fatal error: Argument 1 passed to ElePHPant::__construct() must be of the type string, integer given
// Also for internals funcs
$foo = sin(1);
// Catchable fatal error: sin() expects parameter 1 to be float, integer given
```
I love this because your not forced to use this new feature. You can add it to your existing code gradually.
What do you think about it ?