-1

I'm hitting a wall with this. It's difficult to find an answer because I'm not sure how to word the question, and I can't think of decent keywords either.

I'm writing a view object for use in an MVC framework I'm writing and it assembles pages by tying script outputs together. I'm stuck on the tie together part!

script1.php:

<?php

$variable = solution('/path/to/script2.php');
echo $variable;

?>

script2.php:

<?php

// generates a random md5 hash just for example

mt_srand(microtime(true)*100000 + memory_get_usage(true));
$randommd5 = md5(uniqid(mt_rand(), true));
echo $randommd5;

?>

How do I make both of these scripts return the same value every time I run script1.php?

Is there a PHP function for this purpose? If not, is there a simple and stable way of accomplishing this?

ch7527
  • 203
  • 1
  • 6

3 Answers3

2

Personally, I would wrap it in a function. If you wanted to include a function script, you could do this:

script1.php

 include('script2.php'); //now all functions and variables are available to script1
 $variable = md5function();

script2.php

 function md5function() {
   mt_srand(microtime(true)*100000 + memory_get_usage(true));
   $randommd5 = md5(uniqid(mt_rand(), true));
   return ($randommd5);
 }

Now script2 returns a variable ($randommd5) which is then assigned to $variable in script1.

rwhite
  • 430
  • 2
  • 11
1

http://php.net/manual/en/function.include.php

If you "return" a value from inside the included file, it should be the return value of the include() call (as per doco).

Not a great way to do it though - functions or other more standard mechanisms are better.

Jon Marnock
  • 3,155
  • 1
  • 20
  • 15
0

This will get you going with functions - passing vars to a function in an include file and getting something back. I have simplified it out a fair amount so it isn't in anyway optimised. Hope it helps :)

script1.php

<?php

include("script2.php");
echo get_hero_name("batman");

?>

script2.php

<?php


function get_hero_name($hero){

switch ($hero) {
    case "batman":
        $return_var = "Bruce Wayne";
        break;
    case "superman":
        $return_var = "Clark Kent";
        break;
    Default:
        $return_var = "Papa Smurf";
        break;
}
return($return_var);

}

?>
Chris
  • 5,516
  • 1
  • 26
  • 30
  • I understand basic functions and includes, I was just hoping for a solution that would have script2.php execute independently from its location in the file system so it could use relative file paths and be called from anywhere. – ch7527 Sep 26 '12 at 01:27
  • That's a little different to how I interpreted your question – Chris Sep 26 '12 at 01:29
  • I guess I worded it poorly as everyone is making the same assumption. – ch7527 Sep 26 '12 at 01:52