General developer forum

=& - Simple question

Picture of Joseph Rézeau
Re: =& - Simple question
Core developersParticularly helpful MoodlersPlugin developersTestersTranslators


Does this mean that in moodle 2.x all those "&" should no longer be there? I can still find quite a lot of them, here are some examples in moodle 2.3.

Or maybe I am totally misunderstanding the "&" meaning?

  • moodle\mod\quiz\editlib.php
    • function quiz_print_randomquestion(&$question, &$pageurl, &$quiz, $quiz_qbanktool)
  • moodle\mod\quiz\lib.php
    • function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
              $courseid, $cmid, $userid = 0, $groupid = 0)
  • moodle\mod\wiki\lib.php
    • function wiki_reset_course_form_definition(&$mform)



Average of ratings: -
Re: =& - Simple question
Core developersParticularly helpful MoodlersPlugin developers
Joseph, I've not looked up the functions you've mentioned above to see them in context. However, as a general rule, they may still be valid, if the parameters are not objects.

If you want to pass an array into a function and have it filled in, or you want to pass in a variable to be filled with a string or integer, then passing by reference is valid (in the function definition, but not at call time). If you are passing an object in to a function, or taking a reference to an object to update it (eg inside a form definition), you should not include the & symbol as PHP5 already passes objects as references.
Average of ratings: Useful (1)
Tim at Lone Pine Koala Sanctuary
Re: =& - Simple question
Core developersDocumentation writersParticularly helpful MoodlersPlugin developers

As Davo says, most, but not all, &s should go, but it is not critcial.

I just wanted to point out that instead of a function like

function return_two_things_nasty($input, &$otherreturnvalue) {
    $otherreturnvalue = 'two ' . $input;
    return 'one ' . $input;

$otherreturnvalue = '';
$firstreturnvalue = return_two_things_nasty('sheep', $otherreturnvalue);

you can instead do

function return_two_things_nice($input) {
    return array('one ' . $input, 'two ' . $input);

list($firstreturnvalue, $otherreturnvalue) = return_two_things_nice('sheep');

That gets rid of one of the reasons you might otherwise pass-by-reference.

Average of ratings: Useful (2)