I recently created two code examples to test how constructors work in php, one with an explicit constructor and other without. Both output was the same.
Is it legal to instantiate a class which has no explicit constructor?
Code with constructor
<?php
class Circle {
const PI = 3.14;
public $radius;
//Constructor method
public function __construct($r) {
$this->radius = $r;
}
public function calculate() {
return 2 * self::PI * $this->radius;
}
}
//Argument passed during instantiating
$C = new Circle(7);
echo ("Circumference of Circle: ".$C->calculate());
?>
Code without Constructor
<?php
class Circle {
const PI = 3.14;
public $radius;
//Non-ideal class mutation method
public function calculate($r) {
$this->radius = $r;
return 2 * self::PI * $this->radius;
}
}
$C = new Circle();
//Argument was passed directly to the method
echo ("Circumference of Circle: ".$C->calculate(7));
?>