php 构造函数的用途
可能的重复:
使用构造函数的好处?
编码员们好。我是 php 中的 OOP 新手。我正在做一个对象和类的项目。在哪里 大多数时候我都会遇到一条
public function __construct(){
}
我无法理解的线。为什么使用它以及它的价值是什么。有人可以告诉我一下吗?我访问了 php.net 网站,但我的疑问尚未消除。
Possible Duplicate:
Benefits of using a constructor?
hello coders. I am newbie to OOP in php. I am doing a project in objects and class. where
most of time I face a line
public function __construct(){
}
I can't understand this. Why its used and what is its value. Can some one tell me about it. I went to the php.net site but my doubt not cleared.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
__construct
的值是用面向对象设计的本机方法初始化任何新创建的对象。因此,
我们可以简单地这样做
:在 MyObject 类中:
The value of the
__construct
is to initialize any newly created object in a method that's native to OO design.So, rather than doing something like this:
We can simply do this:
And within the MyObject class:
实例化类时会自动调用此方法。
还有一个 __destruct() 方法,您可能会猜到,当类被销毁时会自动调用该方法。
在这里阅读:
http://php.net/manual/en/language.oop5.decon.php
This method is automatically called when a class is instantiated.
There is also a
__destruct()
method, which as you might guess is automatically called when a class is destroyed.Have a read here:
http://php.net/manual/en/language.oop5.decon.php
__construct 允许在初始化时将参数传递给对象,而无需您执行以下操作:
但如果您有这样的操作:
您可以这样做:
构造函数的另一种可能用途(尽管不是好的做法):
The __construct allows arguments to be passed to an object on initalisation, without you would do something like this:
But if you have this:
You can just do:
Another possible use for the constructor (though not good practice):
它是类中的一个方法。当您从类构造对象时,将调用此关联的构造函数。它有“__”魔术方法前缀。
It's a method within a class. When you construct an object from a class, this associated constructor is called. It has the "__" magic method prefix.
使用 oop 时,构造函数提供对象的基本初始化详细信息。
请参阅:
http://en.wikipedia.org/wiki/Constructor_(object-面向编程)#PHP
when using oop, a constructor gives basic initialization details for an object.
See:
http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)#PHP