PHP: using a variable inside a function

I have:

include ('functions.php'); check_blocked(); echo $blocked; 

in functions.php, check_blocked (); exist. Inside check_blocked, I got:

 global $blocked; $blocked = '1234'; 

I want echo $ to block the variable inside check_blocked ().

It does not work, there is no way out.

This is an example of my original problem, so please do not say that I could just get an echo inside the function, as I cannot have in my source code.

+4
source share
5 answers

Your code should look like

 $blocked = 0; include('functions.php'); check_blocked(); echo $blocked; 

With function.php similar to

 function check_blocked(){ global $blocked; $blocked = 1234; } 

You must define a lock outside the scope of the function before globally locking the function.

+4
source

Why not just return the value?

 function check_blocked() { $blocked = '1234'; return $blocked; } 

then

 include ('functions.php'); echo check_blocked(); 

Avoid global opportunities where possible.

+4
source

If a variable is not declared outside the check_blocked () function, you cannot.

 $foo = null; function check_blocked() { global $foo; $foo = "Hello"; // do some stuff } global $foo; echo $foo; // prints "Hello" 

If it is defined inside a function:

 function check_blocked() { global $foo; $foo = "Hello"; // other work } global $foo; echo $foo; // Nothing 

then the variable is localized locally and discarded as soon as the function completes.

0
source

You can modify check_blocked() to return $blocked , or you can try:

 include ('functions.php'); check_blocked(); global $blocked; echo $blocked; 
0
source

use the return value instead. globals are bad.

 include ('functions.php'); echo check_blocked(); function check_blocked() { return '1234'; } 
0
source

Source: https://habr.com/ru/post/1335455/


All Articles