educative.io

Constructor Definition#

correct code would be


<?php
class Shape
{

    public $sides = 0;

    public $name = " ";

    public function __construct(string $name, int $sides)
    { //defining a constructor
        $this->sides = $sides; //initializing $this->sides to $sides
        $this->name = $name; //initializing $this->name to $name
        
    }

    public function description()
    { //method to display name and sides of a shape
        echo "A $this->name with $this->sides sides.";
    }

}

$myShape = new Shape("hexagon", 6, $myShape->description); 



?>

Course: https://www.educative.io/collection/10370001/5669965877215232
Lesson: https://www.educative.io/collection/page/10370001/5669965877215232/5646368521584640

The very first thing that I noticed in your code is the mentioned data types while creating constructor. It is not required to declare what kind of data type you are entering in php. While the second thing is:

$myShape = new Shape("hexagon", 6, $myShape->description); 

The parametrised constructor which we’ve created, contains only two required arguments, right? Then while creating its object, we’ll simply pass the respective values i.e., "hexagon" and 6 and then call the description function separately. We won’t pass it while creating the shape’s object as it is not the parameter of the constructor rather an individual function.

Hope it helps. If you still have any confusions please let us know.
Thank you!