Constructor scope

Can you define a __Constructor as “private”?

Can it be accessed from outside the class if you don’t?

TomTees

You cannot have a __constructor that is private then attempt to initialize the object.
This will not work:


class TestUnit {
  private function __construct () {}
}

$t = new TestUnit(); # Fails because it cannot call "__construct"

Think of new as a shortcut to “$t = TestUnit->__construct()”

I say they should be “protected” instead. Private makes it harder to extend and override classes/objects.

But is it a moot point?

I just like to be detailed in my coding and not get sloppy.

I’m of the school that all attributes should be private, any methods that don’t need to be accessed on the outside.

TomTees

you can specify the constructor as private. It’s often used this way when defining singletons.


class Foo {

    private static $instance;

    private function __construct() {

    }

   public static function getInstance() {
      if (!self::$instance) self::$instance = new Foo;
      return self::$instance;
   }

}

You can’t specify constructor as private, it has to be public. How would you access constructor outside of the class and why? Constructor is really very very simple - a function called when object is initially created.

I got an error similar to the one I posted above when using “protected”, so apparently my only choice is “public”.

TomTees

If you do not want your class to be a singleton, then yes its a moot point. You would need to leave the constructor public.

In addition I agree with logic_earth, unless your certain that the method will not be used from another place make it protected instead of private.