PHP返回引用-'&'来电者需要吗? [英] PHP returning references - '&' necessary in caller?
问题描述
我正在使用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文档中,此处指出<函数中的c0>和调用方中的=&
.我也经历过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,正在创建一个组件.我使用php 5.3.8在xampp上工作
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.
这篇关于PHP返回引用-'&'来电者需要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!