2

I want to increase $x by 1:

$x = 1;

function addOne($x) {
  $x++;
  return $x;
}

$x = addOne($x);

Is there a way to do this with references, so I don't need to return $x, I can just write addOne($x)?

2
  • I think you want to build something more complex out of this right? Otherwise you could just do $x++; :D Commented Jun 16, 2013 at 10:37
  • It does sort of depend on what is being passed as an argument to the function since objects are (kind of) always passed by reference. Commented Jun 16, 2013 at 10:41

2 Answers 2

3

This is what you're looking for, a by-ref parameter indicated by &.

$x = 1;

function addOne(&$x) {
  $x++;
}

addOne($x);

Some notes:

  • By-ref parameters require that the value passed in not be a literal. Given my example above, addOne(5) would throw a fatal exception
  • References are not needed for objects (including stdClass objects), as all objects are passed by reference as of PHP 5.
  • References ARE needed for arrays, as arrays in PHP are not treated as objects
  • If you want a return value of a function passed by reference, you would indicate the reference on the function name (e.g. function &foo()).

More info on references: http://php.net/manual/en/language.references.php

Sign up to request clarification or add additional context in comments.

4 Comments

Was gonna mention giving some info on references in your answer but you beat me to it.
Is there a difference between using the reference in the function declaration, versus in the function call? Like function addOne($x) but then just call it with addOne(&$x)?
@DonnyP This is not C. Calling it that way will issue a warning.
@FloydThreepwood depends on the version of PHP. In newer versions than PHP 5.3, calltime-pass-by-ref will cause a fatal error.
1
$x = 1;

function addOne(&$x) {
    $x++;
}

addOne($x);

The & sign shows that it takes the parameter by reference. So it increments $x in the function and it will also affect the $x variable in the calling scope.

See also: http://php.net/references for a quick overview about them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.