Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Call to private MyObject::__construct() from invalid context

Tags:

php

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?

like image 627
Brian Avatar asked Jan 04 '10 05:01

Brian


3 Answers

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.

like image 67
zombat Avatar answered Nov 05 '22 07:11

zombat


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

$x = MyObject::getInstance();

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

like image 3
Mogogy Avatar answered Nov 05 '22 05:11

Mogogy


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() {

   }
}
like image 3
Danny Michaeli Avatar answered Nov 05 '22 06:11

Danny Michaeli