0

I have a bunch of scripts that I have to port to php 5. They have global $name, $something...; defined in functions. These functions are not in classes. How can I keep those variables in the functions?

An example function

function myTest($str)  
{   
  global $name, $something; 

  if($name['male'] =='Joe') return 5;

} 

I appreciate any help. Thanks.

hakre
  • 193,403
  • 52
  • 435
  • 836
jacobH
  • 1
  • 3
    the above still works in php 5 –  Aug 28 '11 at 20:34
  • Didn;t work for me. register_globals is off on the server and will remain. – jacobH Aug 28 '11 at 20:41
  • That's good to hear, but not relevant. "global" variables are a built-in language construct and not impaired by that. You probably adapted something else. The vars you are using here have way too generic names (the function name too), easily inviting clashes and overwritten values. – mario Aug 28 '11 at 20:43
  • works for me. what php version are you using? –  Aug 28 '11 at 20:45

1 Answers1

0

Because You were using register_globals = On and know You don't, Your also need to add code that inits global variables:

// Variables must be setted
$foo = validateFoo($_GET['foo']); // or $_REQUEST
$bar = validateBar($_GET['bar']); // or $_REQUEST

function test ()
{
  global $foo;
  global $bar;

  return $foo . ' ' . $bar;
}

// Call function using global vars after global vars have been setted
echo test();
petraszd
  • 4,249
  • 1
  • 20
  • 12
  • Although hardly an ideal solution, this is probably the simplest way to fix it. – Jani Hartikainen Aug 28 '11 at 21:07
  • Ideal solution would be to refactor all the code and sometimes it just is not worth it. Think about it. It is some old PHP4 project that relies on ``register_globals``. Aaaaaaa!!! I would like to spend as less time as possible while working with those kind of beasts... – petraszd Aug 28 '11 at 21:18