Image

Imageneftaly wrote in Imagephp

Subprograms instead of Functions

I want to repeat some code in different sections of a PHP script, without having to pass varibles as you do a function. These were called "Subprograms" in BASIC.

I could just:
* Copy+paste multiple copies of the code
* Make a small php file with the tiny section of code & include() the file where I want it
* Copy the code to a string and get PHP to eval() it - example below
* Use GOTO as in the good 'ole BASIC days :D

... but those seem such dirty ways to do it (not very convienent). No joy searching the manual. While functions are similar to subs, they must not be confused. Here is a working example to illustrate the kind of thing you can do with subs:
<?
$code = "echo 'hello'.$whatever; $whatX=$whatever.$_GET['something']; $somethingElse = $_GET['something']*123; setcookie('blah', $whatX); ";

//blah. possibly some stuff here.
$bob = findOutIfIsAliveOrWhatever($person["bob"]);  

  if ($bob == "alive") {
  $whatever = doSomeStuff(); 
  eval ($code);
  } else if ($bob == "half-life"){
  $whatever = "bob is experiencing radioactive decay, and is only half-alive at this stage. ";
  eval ($code); 
  echo $whatX;
  echo 5 + $somethingElse; 
  } else {
  $whatever = "Oh god, don't tell me... bob is dead! He must be!";
  eval ($code); 
  echo $somethingElse * 321; 
  }
?>
So, has anybody ever done subprograms in PHP before?
*EDIT* I concede defeat, will write a hack for subs into PHP itself (I don't work for PHP; PHP works for me).