20

When creating a new object in PHP, I get the following error message:
Fatal error: Call to private MyObject::__construct() from invalid context
I just create the new object and do not try to call the constructor explicitly. Does anyone know what's going on?

1
  • creating a new object will always call the constructor. Commented Jan 4, 2010 at 5:56

3 Answers 3

34

Your MyObject class has a protected or private constructor, which means that the class cannot be instantiated. __construct() functions are always called when an object is instantiated, so trying to do something like $x = new MyObject() will cause a fatal error with a private construction function. (If you do not specifically declare a __construct() function, the parent constructor will be called).

Private constructors are often used in Singleton classes to prevent direct instantiation of an object. If it's not a class that you built, it might have a getInstance() function available (or something similar) to return an instance of itself.

Sign up to request clarification or add additional context in comments.

5 Comments

That worked, I think I've seen people declaring private constructors before. Is there any reason to do this?
The only reason to do it is if you don't wish the class to be instantiated for some reason. As I mentioned in the answer, the Singleton pattern is a popular reason you might do this (en.wikipedia.org/wiki/Singleton_pattern).
Private constructors are often used by PHP implementations of the Singleton pattern, and are sometimes used with Factories. For example, a factory static method of the class can search for locally cached instances of objects and return a reference instead of a new object. Making the constructor private will prevent any accidental bypasses of the factory method.
So, What is the solution?
Singleton is not the only reason to have a private constructor. Sometimes it is nice to be able to disable the constructor by making it private and create one or more named constructors which you do by creating a public static method which intializes an instance and returns it
3

Instead of $x = new MyObject() you could use

$x = MyObject::getInstance(); 

assuming that MyObject is a Singleton and getInstance() function is available.

Comments

3

For me its was that the name of the CLASS was the same name as one of the methods that was private...

for example...

class myClass { public function __construct() { } private function myClass() { } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.