PHP 返回引用 - '&'来电者有必要吗?
我正在使用 joomla 并且我已经阅读了 API,我注意到 JFactory 类有函数返回对对象的引用,但我从互联网收集的示例没有使用 &
使用功能时.
I'm using joomla and i have read through the API and I noticed the JFactory class having functions return a reference to the object but the examples I have gathered from the internet do not use the &
when using the functions.
例如 Jfactory::getSession()
返回对全局会话的引用.文档 显示其定义为 function &getSession(params){code}
- 明确定义引用返回.然而,在这个例子中,他们将其称为 $session = JFactory::getSession();
不应该是 $session =&JFactory::getSession();
?
Say for example the Jfactory::getSession()
which returns a reference to the global session. the documentation shows that its defined as function &getSession(params){code}
- clearly defining a reference return. however, in this example, they call it as $session = JFactory::getSession();
shouldn't it be $session =& JFactory::getSession();
?
它在 php 文档 中指出,有一个 <函数中的 code>& 和调用者中的 =&
.我也学过 C 编程,如果我错过了这样的事情,就会出现无效指针转换"之类的错误——这不是一个好的编程习惯.
It states here in the php documentation that there is an &
in the function and an =&
in the caller. I have also gone through C programming and if I miss things like this, there will be errors like "invalid pointer conversion" - which is not a good programming practice to tolerate.
正确的做法是什么?
附加信息:
我使用 joomla 1.7 并且我正在创建一个组件.我在 xampp 上使用 php 5.3.8
i use joomla 1.7 and i'm creating a component. i work on xampp with php 5.3.8
推荐答案
这取决于:
- Joomla 的版本和您使用的 PHP 版本
- 返回 JFactory::getSession() 方法的内容
It depends on:
- the version of Joomla and the version of PHP you use
- what returns the JFactory::getSession() method
Joomla 1.5 版本兼容 PHP 4 和 PHP 5,1.6 和 1.7 版本仅兼容 PHP 5.
Joomla version 1.5 is compatible with PHP 4 and PHP 5, versions 1.6 and 1.7 are only compatible with PHP 5.
如果该方法返回一个对象,&
在 PHP 4 中是强制性的:默认情况下,对象按值传递/返回(对象的副本发生).&
避免了复制.
在 PHP 5 中,&
是无用的:对象总是通过引用传递/返回(不发生复制).
If the method returns an object, the &
is mandatory in PHP 4: by default, objects are passed/returned by value (a copy of the object occurs). The &
avoids the copy.
In PHP 5, the &
is useless : objects are always passed/returned by reference (no copy occurs).
如果该方法返回任何其他内容,则不应使用 &
但在某些非常罕见的情况下可能很有用(为了节省内存,如果您有一个巨大的数组或字符串,例如例如,您不想在作业中复制它们).
If the method returns anything else, the &
shouldn't be used but can be useful in some very rare cases (in order to save memory if you have a huge array or string, for example, and you don't want of copy of them in the assignment).
当方法签名也包含 &
时,好的做法是始终将 &
放在赋值中.
The good practice is to always put a &
in assignment when the method signature includes a &
too.
就您而言,我认为您使用的是 PHP 5 和最新版本的 Joomla,所以不要使用 &
:这可能是 Joomla 源代码中的过时代码.
In your case, I think that you're using PHP 5 and a recent version of Joomla, so don't use &
: this is probably an obsolete code in Joomla sources.
相关文章