0

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.

Alberto Acuña
  • 512
  • 3
  • 9
  • 28

1 Answers1

1

$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
  • what if inside functions.php im calling to another funcion? where i shoulde declare it as global, in the first one or in the second one? – Alberto Acuña Sep 01 '16 at 17:42
  • I mean if I have to use it in more than 1 function, there is a way to declare global just once instead of each time in each function? thanks – Alberto Acuña Sep 01 '16 at 17:46
  • @AlbertoAcuña you must declare global variable 1 times in every function if you want use it. – buivankim2020 Sep 01 '16 at 17:46
  • **Using globals is a terrible idea in this case** Pass the variable as a function parameter like `function get_val($val) {return $val * 2;}` – RiggsFolly Sep 01 '16 at 20:52