DEV Community

pcreem
pcreem

Posted on

PHP8 constructor type test experiment

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

to

class Point {
  public function __construct(
    public float $x = 0.0,
    public float $y = 0.0,
    public float $z = 0.0,
  ) {}
}
Enter fullscreen mode Exit fullscreen mode

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();
?>
Enter fullscreen mode Exit fullscreen mode

The output

the string case
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

works well

check number in string test

turn 'the string case' to 123

The output

123
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)