0

I am trying to make the $x output the static nature as I have tried in the code below, I wasn't able to do that simple so i tried using the global array (as i can't access the variable that i declared outside the function), So i tried using the global array which didn't work either, next I tried to achieve the same by using the global keyword , but latter didn't work either can someone suggest me what i am doing wrong?

<?php
global$x=5;
global$y=10;
global static $s=0;
$s=$x + $y;
//echo $s;
function willthiswork(){
//GLOBAL['s']=GLOBAL['x']+GLOBAL['y'];
$s=$x+$y;
$s++
}
willthiswork();
willthiswork();
willthiswork(); 
?>

I am really new with php and using this link to learn if there's any better resource please do mention it. https://www.w3schools.com/php/php_variables.asp

Dixon
  • 23
  • 5

2 Answers2

0

global keyword is used inside function

function willthiswork(){
   global $x, $y;
   $s=$x+$y;
   $s++
}
Goms
  • 1,921
  • 3
  • 13
  • 32
  • is there any way to access the vars from outside of the function and still be able to print the static nature i.e expected output `0 1 2` – Dixon Jan 12 '18 at 10:09
0

Global var is bad practice here's a link

you can use default parameters like this

function myTest($x = 5) {
  echo "<p>Variable x inside function is: $x</p>";
}
myTest(); //default x = 5
myTest(6) // will print x = 6

hope it helps

sancoLgates
  • 158
  • 9