1

I have the following PHP code, which is stored in a seperate PHP file to the index.php file I am using.

The page include()'s fine into the index.php file when not within a function.

 $_3_dart_score = $_POST["user-input"];
 $remaining_score = 501 - $_POST["user-input"];

However when it is included with an function, it doesn't seem to work.

<?php
function throw()
{
$_3_dart_score = $_POST["user-input"];
$remaining_score = 501 - $_POST["user-input"];
global $_3_dart_score
global $remaining_score
throw();
}
?>

I have tried all sorts, even calling the function from the index.php page, however nothing seems to work.

John Conde
220k99 gold badges464 silver badges504 bronze badges
asked Mar 20, 2015 at 0:08
3
  • 1
    Your function is calling itself which I highly doubt you want Commented Mar 20, 2015 at 0:08
  • Fair point. I will try again with a loop. Thanks Commented Mar 20, 2015 at 0:09
  • You don't really want a function accessing global variables like that. Pass them is as arguments, like: function throw($input, $otherinput) {... Commented Mar 20, 2015 at 0:11

2 Answers 2

1

You need to call throw() from outside of your function, not inside of it. You should also consider passing variables as arguments instead of relying on global variables.

answered Mar 20, 2015 at 0:11
1
function throw($input) {
 $_3_dart_score = $input;
 $remaining_score = 501 - $input;
 return array($_3_dart_score, $remaining_score);
}
list($_3_dart_score, $remaining_score) = throw($_POST["user-input"]);
  1. Get rid of the global nonsense. That's bad form. Instead return those values. I use an array so I can return both at once. (They actually should be done separately in different functions but you're not quite there yet).

  2. I pass $_POST["user-input"] as a parameter to throw() as your function should not be so closely tied to other code. This way that value can come from anywhere and this function will still work.

  3. I use list() to put those values in the array into there own scalar variables in a one-liner.

answered Mar 20, 2015 at 0:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.