I have an abstract class that has a function which uses PHP's Late Static Binding, as follows:
abstract class MetaComponent {
public static function do(...$args) {
return new static(...$args);
}
}
Then, I implemented the abstract class this way:
class ¬Text extends MetaComponent {
private function __construct(string $text) {
$this->text = $text;
}
public function render() {
echo $this->text;
}
}
My intention was that no one could instantiate ¬Text
directly, so I made the __construct
function private. However, anyone should be able to instantiate it through ¬Text::do('Lorem Ipsum')
. This is why I used Late Binding Static within MetaComponent::do()
.
However, I get the following error:
PHP Fatal error: Uncaught Error: Call to private ¬Text::__construct() from context 'MetaComponent' in /xxx/MetaComponent.php:9
Is there a way to call the constructor from the abstract class while preventing __construct
from being called directly?