Avatar of Crazy Horse
Crazy Horse
Flag for South Africa asked on

function available outside function?

I am still trying to wrap my head around functions and scope.

I thought that you couldn't call a function from outside of a function yet I have taken an example from W3 Schools website

if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

Open in new window


Unless I am so confused I am missing something, it looks like:

 $gender = test_input($_POST["gender"]);

Open in new window


is being used outside of the actual test_input function and this works. I thought it wouldn't work because it's outside the function. Or am I misunderstanding?
PHP

Avatar of undefined
Last Comment
zephyr_hex (Megan)

8/22/2022 - Mon
zephyr_hex (Megan)

The first segment of code is not a function.  It's a conditional statement, and as such, it is in the same realm / scope as the test_input function.

That being said, some IDE's will throw a warning because the function should be written above the point where it's called.  In other words, the function should appear before the conditional statement.
Crazy Horse

ASKER
Yeah, I also thought it strange that they had the function at the bottom but that is how they did it.

Could I make it all into one function if I wanted to use it all as a form validation function?

function test_input($data) {
    
    $message = "";
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;

if (empty($_POST["gender"])) {
    $message .= "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
          }
    
    if($message) {
        
        echo "There were errors in your form:<br>" . $message;
        
    } else {
        
        //submit form
   }
     }

Open in new window

ASKER CERTIFIED SOLUTION
zephyr_hex (Megan)

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes