PHP:在构造函数中使用 $this
我有一个在 php 中使用这种语法的想法。它说明了创建对象有不同的后备方法
function __construct() {
if(some_case())
$this = method1();
else
$this = method2();
}
这是一场噩梦吗?或者它有效吗?
I have an idea of using this syntax in php. It illustrates that there are different fallback ways to create an object
function __construct() {
if(some_case())
$this = method1();
else
$this = method2();
}
Is this a nightmare? Or it works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这不起作用。您无法取消设置或从根本上更改在构造函数中创建的对象。您也可以不设置返回值。您所能做的就是设置对象的属性。
解决这个问题的一种方法是拥有一个单独的“工厂”类或函数,它检查条件并返回正确对象的新实例,如下所示:
另请参阅:
It doesn't work. You can't unset or fundamentally alter the object that is being created in the constructor. You can also not set a return value. All you can do is set the object's properties.
One way to get around this is having a separate "factory" class or function, that checks the condition and returns a new instance of the correct object like so:
See also:
为什么不做一些更常见的事情,例如:
Why not to do something more common like:
您可以只创建类方法 method1 和 method2 并编写
You can just create class methods method1 and method2 and just write
您可以制作工厂方法。
例子:
You can make factory method.
Example:
听起来有点像 单例类模式。
It sounds a little bit like the Singleton class pattern.
请参阅@Ivan 的回复等,了解您想要执行的操作的正确语法。
但是,还有另一种选择 - 使用静态方法作为替代构造函数:(
注意:你绝对不能在静态方法中使用
$this
)See @Ivan's reply among others for the correct syntax for what it looks like you're trying to do.
However, there are is another alternative - use a static method as an alternative constructor:
(note: you definitely can't use
$this
in a static method)如果你想共享一些功能,请执行一些类似的操作
并调用类似的操作
If you want to share some functions, do some like
And call like