Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function initialize a variable in PHP?

Tags:

variables

php

Without specifically doing so,

Like:

function init($var){
  $var = 'x';
}

function a(){
  init($foo);

  echo $foo; // should be x

}

Something like the list() function :)

like image 674
Alex Avatar asked Dec 10 '22 05:12

Alex


2 Answers

Pass by reference:

function init(&$var){
  $var = 'x';
}
like image 197
Tim Cooper Avatar answered Dec 11 '22 18:12

Tim Cooper


Sure. You can pass the parameter by reference. So you have to change this

function init($var)

into this:

function init(&$var)
like image 31
Aurelio De Rosa Avatar answered Dec 11 '22 17:12

Aurelio De Rosa