PHP returning references - '&' necessary i

2019-07-17 02:29发布

问题:

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.

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();?

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.

What is the proper practice?

Additional info:

i use joomla 1.7 and i'm creating a component. i work on xampp with php 5.3.8

回答1:

It depends on:
- the version of Joomla and the version of PHP you use
- what returns the JFactory::getSession() method

Joomla version 1.5 is compatible with PHP 4 and PHP 5, versions 1.6 and 1.7 are only compatible with 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.

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.