-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?

1
  • 4
    Have you read about functions yet? Commented Sep 26, 2012 at 0:57

3 Answers 3

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.

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

Comments

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.

Comments

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);

}

?>

3 Comments

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.
That's a little different to how I interpreted your question
I guess I worded it poorly as everyone is making the same assumption.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.