php 致命错误:从无效上下文调用私有 MyObject::__construct()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1997721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fatal error: Call to private MyObject::__construct() from invalid context
提问by Brian
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?
在 PHP 中创建新对象时,我收到以下错误消息:Fatal error: Call to private MyObject::__construct() from invalid context
我只是创建了新对象,并没有尝试显式调用构造函数。有谁知道发生了什么?
回答by zombat
Your MyObjectclass 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).
你的MyObject类有一个受保护的或私有的构造函数,这意味着该类不能被实例化。 __construct()函数总是在实例化对象时调用,因此尝试执行类似操作$x = new MyObject()将导致私有构造函数出现致命错误。(如果没有特别声明一个__construct()函数,就会调用父构造函数)。
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.
私有构造函数通常用于单例类中,以防止对象的直接实例化。如果它不是您构建的类,它可能有一个getInstance()可用的函数(或类似的东西)来返回它自己的一个实例。
回答by Mogogy
回答by Danny Michaeli
For me its was that the name of the CLASSwas the same name as one of the methods that was private...
对我来说,CLASS的名称与私有方法之一的名称相同......
for example...
例如...
class myClass {
public function __construct() {
}
private function myClass() {
}
}

