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));
?>
Adding a constructor method is optional. The documentation states:
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object.
Note however that your second implementation is not ideal:
the calculate
method has a side-effect: it sets the radius member. This is not best practice: if a method's main purpose is to return something, then it should not mutate the object.
the calculate
method requires you to provide the radius on every call. This is not really what you want when the object is supposed to know its radius.