Jump to content

var not in function.


MarcCools

Recommended Posts

Hi,This is my code within a HTML document: :)<?php$TEST1 = "T_E_S_T_1";function ToonTest(){ $TEST2 = "T_E_S_T_2"; echo "$TEST1"; echo "<br>"; echo "$TEST2"; }ToonTest();?>This is the result: :) T_E_S_T_2 PHP Notice: Undefined variable: TEST1 in testFunctionVar.php on line 22 Why doesn't the function get acces to the $TEST1 variabele and how can it be solved? :) Thanks.

Link to comment
Share on other sites

You're going to have to pass the variable to the function:

$TEST1 = "T_E_S_T_1";function ToonTest($V){$TEST2 = "T_E_S_T_2";echo "$V";echo "<br>";echo "$TEST2";}ToonTest($TEST1);

Link to comment
Share on other sites

As a general rule of programming, global variables should be kept to a minimum, and passing external values to functions by argument (Ingolme's solution) is to be preferred.However, functions in CGI scripts often need to evaluate a lot of variables, and since the scripts rarely run for more than a few milliseconds (unlike a user application) there is little risk that an abundance of globals will bust your memory resources.By definition, variables declared outside a function are global. Also by definition, they are invisible inside a function unless you declare them as global. This lets you have access to the global variable without having to pass it as an argument.So, to function toonTest(), you can add this line:global $TEST1;That's all it takes.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...