2

How can I define a class that can only be instantiated without parameters, and forbids instantiation when any parameters are passed to the constructor?

My goal is to enforce a certain set of classes that are supposed to be "simple" and be used as a template. As part of that, I don't want anything to be passed to the constructor during instantiation.

When anything is passed via constructor, I want things to fail (RunTime Error, Fatal Error, Static interpreter error check, etc)

class Template()
{
    ...
}

new Template(); // okay
new Template($anything); // must not work
Dennis
  • 7,907
  • 11
  • 65
  • 115

2 Answers2

4

Just raise an exception if anything was passed:

class Foo {
    public function __construct(...$args) {
        if (count($args) > 0) {
            throw new Exception('No arguments!');
        }
    }
}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 2
    (note on the `...` splat operator - PHP >=5.6 only, so consider that if you have to support older versions _(which I hope you don't)_) – Michael Berkowski Aug 23 '18 at 19:57
2
class Test {

    public function __construct() {
        if (func_get_args()) {
            throw new Exception('No parameters are allowed.');  
        }
    }

}

try {
    $p = new Test('test');
} catch (Exception $e) {
    echo $e->getMessage();  
}
kidA
  • 1,379
  • 1
  • 9
  • 19
  • 1
    `func_num_args()` is slightly better here, because we don't care what they are, only if there are some. I thought about using it in an answer, but it's not a difference worthy of another answer. – ArtisticPhoenix Aug 23 '18 at 20:08