PHP8 simplify constructor method from
//php7 version
class Point {
public float $x;
public float $y;
public float $z;
public function __construct(
float $x = 0.0,
float $y = 0.0,
float $z = 0.0
) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
}
to
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
write a simple case
<?php
class Point {
public function __construct(
public string $name
) {}
public function returnVal(){
return $this->name;
}
}
$testClass = new Point('the string case');
print $testClass->returnVal();
?>
The output
the string case
check array in string test
turn 'the string case'
to ['the string case']
The output
PHP Fatal error: Uncaught TypeError: Point::__construct(): Argument #1 ($name) must be of type string, array given
works well
check number in string test
turn 'the string case'
to 123
The output
123
There's no type error warning.
add declare(strict_types=1);
to the top of code
The output
PHP Fatal error: Uncaught TypeError: Point::__construct(): Argument #1 ($name) must be of type string, int given
Top comments (0)