通过引用或值传递对象
我确信这个问题已经被问过一千次了,但我很难找到一个我可以理解或在任何地方使用的答案。
在我的项目中,我需要在很多类中使用我的 sql 类和其他杂项类。然后我很想知道传递对象的最佳性能方式是什么。
我应该将对象传递给类构造作为参考吗?
class MyClass {
private $_link;
function __construct(&$db) {
$this->_link =& $db;
}
}
或值..
class MyClass {
private $_link;
function __construct($db) {
$this->_link = $db;
}
}
或只是创建一个新对象?
class MyClass {
private $_link;
function __construct() {
$this->_link = new DB();
}
}
I'm sure this question has been asked a thousand times, but i had trouble finding an answer i could understand or use anywhere.
In my project, i need to use my sql class and other misc classes, in alot of the classes. Then i'm qurious to know what's the best way performance wise to pass the objects.
Should i pass the objects to the classes construct as reference?
class MyClass {
private $_link;
function __construct(&$db) {
$this->_link =& $db;
}
}
or value..
class MyClass {
private $_link;
function __construct($db) {
$this->_link = $db;
}
}
or simply create a new object?
class MyClass {
private $_link;
function __construct() {
$this->_link = new DB();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 PHP5+,则在几乎所有情况下,默认情况下对象都是通过引用传递的。
If you are using PHP5+, in almost all cases, objects are passed by reference by default.
由于对象已经在 PHP5+ 中“通过引用”传递,因此使用
&
您实际上会传递“对对象引用的引用”,而不仅仅是简单的“对对象的引用”。这可能很关键,因为它将允许其本地范围内的函数全局更改实际引用,并可能完全删除该对象。例如,人们会认为以下通过 ref 传递对象和通过“正常”传递对象的示例完全相同:从输出来看,它看起来是相同的。但这是一个好的做法吗?取决于你想做什么。看一下我们销毁原始引用并“删除”对象的同一个示例:
代码不言自明。在某些情况下这是必要的,而在其他情况下这是至关重要的。在我看来,除非你真的知道你在做什么,否则不要通过引用。
As objects are already passed "by reference" in PHP5+ then using
&
you would actually pass a "reference to a reference to an object" not just a simple "reference to an object". This can be critical because it will allow the function within its local scope to change the actual reference globally and potentially remove the object entirely. For example one would think that the following example of passing the object by ref and passing by "normally" is completely the same:Judging by the output it looks the same. But is it a good practice? Depends what you wanted to do. Look at the same example where we destroyed the original reference and "deleted" the object:
The code speaks for itself. In some cases this is needed, in other this is critical. In my opinion unless you really know what are you doing do not pass by reference.