Get a variable in a function within another function PHP - php

help me get variable in a function within another function
$variable ="alfa";
function foo(){
$variable ="beta";
$my_function = function(){
global $variable;
return $variable;
};
return $my_function();
}
I want the function foo(); print "beta" no "alpha", what's wrong with my code?
print foo(); // this print "alpha" and should print "beta"

Use use instead of global.
$variable ="alfa";
function foo(){
$variable ="beta";
$my_function = function() use ($variable){
return $variable;
};
return $my_function();
}
You can read more about it in docs example #3

You should declare global $variable; before assigning $variable ="beta";.
If not, you are working in the function scope, not global scope.

Try to clear the concept of " Scope of the variables "
inside the function foo() , you declare the variable $variable, Then in the anonymous function you are accessing the $variable you have declared inside the foo(), So if you want to use the global $variable inside the anonymous function, You should make the global $variable right after you declare the function foo()
$variable ="alfa";
function foo(){
global $variable;
$variable ="beta";
$my_function = function(){
global $variable;
return $variable;
};
return $my_function();
}

Related

why the unset function is different between global and $GLOBALS?

Question
why the unset function is different between global and $GLOBALS ?
here is my code , the $GLOBALS version will echo nothing ,but the global will echo "hi".
//$GLOBALS version
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar ="hi";
foo();
echo $bar;
?>
the code above echo nothing
but when i change $GLOBALS['bar'] to global $bar ,it echo "hi"
//global version
<?php
function foo()
{
global $bar;
unset($bar);
}
$bar = "hi";
foo();
echo $bar;
?>
I have search in google and php manual , but it seems not detail about this problem .
what is the difference between GLOBALS and GLOBAL?
A true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. When you use unset() it unsets the variable that is referencing the global variable, the same as other references. When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:
$a = 1;
//assign a reference to $a
$b =& $a;
unset($b);
var_dump($a);
Yields: int(1) See Unsetting References.
When you access $GLOBALS you are accessing a superglobal array and unsetting the actual variable contained in the array.

PHP scope issue in anonymous function

so I have these functions
function a(){
int c = 1;
b(function(){echo $c;});
}
function b($code){
$code();
}
but somehow $c becomes undefined in the anonymous function
I know it's bacause that the anonymous function is it's own scope, but is there someway to make this work?
Yes: you can use "use" statement.
function a()
{
$c = 1;
b(function() use ($c) {
echo $c;
});
}
function b($code){
$code();
}
http://php.net/manual/en/language.variables.scope.php
When you put $c inside a function it's considered to be a local scope variable.

Global scope not printing data

Why is $a not printing?
And what is the alternate of this, and I dont want to use return.
function abc () {
$a = 'abc';
global $a;
}
abc();
echo $a;
The reason why it's not echoing is because of two things:
1) You need to declare global "before" the variable you wish to define as being global.
and
2) You also need to call the function.
Rewrite:
<?php
function abc()
{
global $a;
$a = 'abc';
}
abc();
echo $a;
For more information on variable scopes, visit the PHP.net website:
http://www.php.net/manual/en/language.variables.scope.php
You can get your variable as:
echo $GLOBALS['a'];
see http://php.net/manual/en/language.variables.scope.php
You can use define():
function abc() {
define("A", "abc");
}
abc();
echo A;
Make sure you call the function. I added that just above echo.
First you must create and assign a variable. And then in you function describe that is a global var you want to use.
$a = 'zxc';
function abc() {
global $a;
$a = 'abc';
}
abc();
echo $a;
This is not really good idea to use golbal such way. I don't really understand why I so much want to use a global var...
But my opinion is better for you to use a pointer to variable.
function abc(&$var){
$var = 'abc';
}
$a = 'zxc';
abc(&$a);
echo $a;
Or even would be better to create an object and then access variable with-in this object

PHP variable defined outside callback function is unaccessible inside the function

I'm trying to use $variable inside my callback function. I pass it to another function like this: functionName("egTraders_ItemDataBound"), inside that function I assign it to a variable and the call it like this: $theAssignedFunctionVariable($this, $rowToAdd);
And the function egTraders_ItemDataBound gets called properly but the variable $variable
is undefined. What can I do?
<?php
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
echo $variable;
}
?>
If You are running PHP 5.3+ You can achive this by simply creating anonymous functioin with use keyword ( documentation ) :
$bar = 'bar';
$f = function() use ($bar)
{
var_dump($bar);
};
function bar( $fName )
{
$fName();
}
bar($f);
You could pass it in as a param or you could use it as a global in the function. I do not recommend the latter. You should stay away from globals.
Edit for example
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
global $variable;
echo $variable;
}
egTraders_ItemDataBound(NULL, NULL);
you need to declare the variable as global because it is out of scope
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
global $variable;
echo $variable;
}
The variable is declared outside of the scope of the function. You should revisit your design. I strongly recommend against using global variables as that is poor practice.

Declaring a global variable inside a function

I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is some code which I'm using in join.php:
include('inc/processJoin.php');
setcookie("site_Referral", $_GET['rid'], time()+10000);
$joinProc = new processJoin();
$joinProc->grabReferral($_COOKIE["site_Referral"]);
The other file (processJoin.php) will then send this value (among others) to further files which will process and insert the data into the database.
The problem I'm having is that when the grabReferral() function in processJoin.php is called, the $referralID variable isn't being defined on a global scale - other functions in processJoin.php can't seem to access it to send to other files/processes.
I've tried this in processJoin.php:
grabReferral($rid) {
global $ref_id;
$ref_id = $rid;
}
someOtherFunction() {
sendValue($ref_id);
}
But the someOtherFunction can't seem to access or use the $ref_id value. I've also tried using define() to no avail. What am I doing wrong?
you have to define the global var in the second function as well..
// global scope
$ref_id = 1;
grabReferral($rid){
global $ref_id;
$ref_id = $rid;
}
someOtherFunction(){
global $ref_id;
sendValue($ref_id);
}
felix
personally, I would recommend the $GLOBALS super variable.
function foo(){
$GLOBALS['foobar'] = 'foobar';
}
function bar(){
echo $GLOBALS['foobar'];
}
foo();
bar();
DEMO
This is a simple and working code to initialize global variable from a function :
function doit()
{
$GLOBALS['val'] = 'bar';
}
doit();
echo $val;
Gives the output as :
bar
The following works.
<?php
foo();
bar();
function foo()
{
global $jabberwocky;
$jabberwocky="Jabberwocky<br>";
bar();
}
function bar()
{
global $jabberwocky;
echo $jabberwocky;
}
?>
to produce:
Jabberwocky
Jabberwocky
So it seems that a variable first declared as global inside a function and then initalised inside that function acquires global scope.
The global keyword lets you access a global variable, not create one. Global variables are the ones created in the outermost scope (i.e. not inside a function or class), and are not accessible inside function unless you declare them with global.
Disclaimer: none of this code was tested, but it definitely gets the point across.
Choose a name for the variable you want to be available in the global scope.
Within the function, assign a value to the name index of the $GLOBALS array.
function my_function(){
//...
$GLOBALS['myGlobalVariable'] = 42; //globalize variable
//...
}
Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.
<?php
//<global scope>
echo $myGlobalVariable; //outputs "42"
//</global scope>
?>
To access your global variable from a non-global scope such as a function or an object, you have two options:
Access it through the appropriate index of the $GLOBALS array. Ex: $GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.
A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.
//<non global scopes>
function a(){
//...
global $myGlobalVariable;
echo $myGlobalVariable; // outputs "42"
//...
}
function b(){
//...
echo $GLOBALS['myGlobalVariable']; // outputs "42"
echo $myGlobalVariable; // outputs "" (nothing)
// ^also generates warning - variable not defined
//...
}
//</non global scopes>
Please use global variables in any language with caution, especially in PHP.
See the following resources for discussion of global variables:
http://chateau-logic.com/content/dangers-global-variables-revisited-because-php
http://c2.com/cgi/wiki?GlobalVariablesAreBad
The visibility of a variable
I hope that helped
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>

Categories