1

I'm new to PHP, i made some research but couldn't find a clear answer. In a functions.php file i have a function that contains some variables that i need, and a classes.php file containing a class with a method that needs the values from the variables of the function in functions.php. The Question is: why the echoed variable is outputted but the other variables are called as Undefined.And how can i call and use them.

Example:

functions/functions.php

<?php
// functions.php file

function incFunc(){
    $inc_var1 = "Marco";
    echo $inc_var1; //this variable output Marco without problem
    echo "<br>";
    echo "<br>";
    $inc_var2 = "Polo"; //this is the variable i want to use in the class method.
}
?>

classes/classes.php

<?php
// classes.php file

include '../functions/functions.php';
class theClass
{   
    public function classFunc(){
        incFunc();
        echo $inc_var2; //Notice: Undefined variable: inc_var2
    }
}
$obj = new theClass();
$obj->classFunc();
?>

Outputs:

Marco

Notice: Undefined variable: inc_var2 in...

Community
  • 1
  • 1
  • 3
    functions have their own scope - all you do is execute the first function, where you echo the first var inside the first function. – treyBake Oct 09 '19 at 14:02
  • thank you for your answer, i couldn't find or i guess i have missed out to find the answer in other already existing questions here. – Alex.sandar Oct 09 '19 at 14:50

1 Answers1

0

If you want to use variables from incFunc function scope in the class you have to return the value Example:

function incFunc($returnVar){
   $inc_var1 = "Marco";
   $inc_var2 = "Polo";
   if ($returnVar == 'var1') {
      return $inc_var1;
   } else {
      return $inc_var2;
   }
}

Than,in your class method, save the result of a function in an variable:

public function classFunc(){
    $inc_var1 = incFunc('var1');
   // do stuff
}

This is just a basic example, if you want to include multiple variables at once, you can return an array instead of single variables.

failedCoder
  • 1,346
  • 1
  • 14
  • 38