Alberto Acuña Alberto Acuña - 3 months ago 10
PHP Question

I cant get a variable from my main.php using a require_once return data php

This is what im trying to do:

I have a index.php and what im trying to do is read a value from this one, in another php using require_once, and returned the value modified, but it doesnt work for some reason, thanks everyone.

functions.php

<?php
function get_val(){
return $my_val*2;
}
?>


index.php

<?php
$my_val = 3;
require_once "functions.php";
echo get_val();
?>


So if u can help me, what i need to show is 6; but it doesnt show anything, i dont wanna use arguments, only global variables but it doesnt work,thanks.

Answer

$my_val variable is scope in function, you must use global variable in this case, example here:

functions.php

<?php
  function get_val(){
    global $my_val;
    return $my_val*2;   
  }
?>

index.php

<?php
  $my_val = 3;
  require_once "functions.php";
  echo get_val();
?>

you can see example here (From w3s)

<?php
$x = 5;
$y = 10;

function myTest() {
    global $x, $y;
    $y = $x + $y;
} 

myTest();  // run function
echo $y; // output the new value for variable $y, result: 15
Comments