How can I use variable in another file?

Here I am trying to give an error message in my index.php from the file emailValidation.php. I am trying to use $emailMessage which is located in emailValidation.php.
Here is the error I am getting: Notice : Undefined variable: emailMessage in D:\XAMPP\htdocs\magebit_test\index.php on line 49

this is index.php

    <?php
      include 'database/emailValidation.php';
      include 'database/subscribers.php';
      $subscribers= new subscribers();
      $subscribers->insertSubscribers();
      $validation = new emailValidation();
      $validation->validation();
      // include 'database/viewSubscribers.php';
     ?>

    <span><?php echo $emailMessage ?></span>

This is my emailValidation.php

    <?PHP

    class emailValidation {
    function checkemail($email) {
        return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email) ) ? FALSE : TRUE;
    }
    
    function columbia($email){
        return (!preg_match("/@([\w-])+\.co$/mi", $email)) ? FALSE : TRUE;
    }

    function validation(){
        if(isset($_POST['emailSubmit'])){
            if (empty($_POST["emailText"])) {
              $emailMessage = "Email is required";
            } else {
              $email = $_POST["emailText"];
              if (!checkemail($email) || columbia($email)) {
                $emailMessage = "Invalid email format";
              }
            }
          }
      }
    }

If you for some reason trying to make that a class… perhaps you need to define it as a public var first?

You are creating the value you want inside a function; the value is no longer available once the function has finished running. However, functions can return a value to the code that calls them. That’s what you need to use here. In your emailValidation class:

function validation(){
  if(isset($_POST['emailSubmit'])){
    if (empty($_POST["emailText"])) {
      $emailMessage = "Email is required";
    } else {
      $email = $_POST["emailText"];
      if (!checkemail($email) || columbia($email)) {
        $emailMessage = "Invalid email format";
      }
    }
  }

  // This line is new
  return $emailMessage;
}

In your index.php:

// .. rest of your code was above here
// This line now assigns a value to $emailMEssage locally
$emailMessage = $validation->validation();
?>

<span><?php echo $emailMessage ?></span>

As an aside; you should make sure you understand how functions work fully before using classes, since a class cant do much without them.

1 Like

Alternately… it could be set as a public var… so a function isnt needed to return it every time…

Thank you for your reply.
Your solution is really good.
I have already found the solution :slight_smile:

Thank you for your answer.
I have already found the solution :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service