Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Constructor Property Promotion in PHP 8

  • Last Updated : 22 Jul, 2021

Constructor Property Promotion is a simple shorthand syntax to declare and assign class properties from the constructor. Constructor Property Promotion is a new syntax provided in the newer version of PHP 8 that allows class property declaration and constructor assignment right from the constructor without getting in the condition of boilerplate code.

In computer programming, boilerplate code is sections of code that are repeated in multiple places with little or no variation which makes code repetitive, complex, and uneasy to see. Before this new update in PHP, we have to repeat variables in the constructor as shown below.

Example 1:

PHP




<?php
  
class GFG {
    public $name;
    public $university;
  
    // Boilerplate code
    function __construct($name, $university) {
        $this->name = $name;
        $this->university = $university;
    }
    function get_name() {
        return $this->name;
    }
    function get_university() {
        return $this->university;
    }
}
  
$a = new GFG("Atul Sisodiya", "JECRC");
echo $a->get_name();
echo "<br>";
echo $a->get_university();
  
?>

 



Output:

Atul Sisodiya
JECRC

Example 2: After the latest update in PHP version 8, it provides Constructor Property Promotion of simpler syntax.

PHP




   
<?php
  
class GFG {
    public function __construct(
        public string $name
        public string $university) {
           $this->name = $name;
           $this->university = $university;
        }
          
    function get_name() {
        return $this->name;
    }
    
    function get_university() {
        return $this->university;
    }
}
   
$a = new GFG("Atul Sisodiya", "JECRC");
echo $a->get_name();
echo "<br>";
echo  $a->get_university();
  
?>

Output:

Atul Sisodiya
JECRC



My Personal Notes arrow_drop_up
Recommended Articles
Page :