get a variable from the scope where the function used not Global - php

how to access the variable X in Function Func1 not in global Scope
$X='hi';
function Func1(){
global $X;
echo $X;
}
function Func2(){
$X='hello';
Func1(); // I want to echo "hello" not "hi"
}

(First of all, good job trying to avoid using a global. They are almost never the right answer.)
Variables in PHP functions are locally scoped - they don't inherit anything from where they're called. Func1 has no idea about any variables or anything else that happens in Func2, it only knows about itself.
If you want a variable available in a function, then you need to pass it in as an argument:
function Func1($X){
echo $X;
}
function Func2(){
$X='hello';
Func1($X);
}
It would be worth reading http://php.net/manual/en/language.variables.scope.php to get a basic grounding in scope in PHP.

Give this a try
$x = 'hi';
function func1(){
echo func2();
}
function func2(){
return $x = 'hello';
}
The x variable will get overridden and the function will return the variable data.
Next, the func2 will be called in func1 and the returned value will be printed on the screen.
Just tried to minimize the number of lines.

Related

Php variable global and static

I am new to PHP.
I'm studying variables scopes.
A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only
be accessed within that function.
The global keyword is used to access a global variable from within a
function.
To do this, use the global keyword before the variables (inside the
function)
Normally, when a function is completed/executed, all of its variables
are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
I need to declare variable within function to be global so I can get access to it from outside the function and to be static at the same time so I can keep the value of the variable after execution of the function and use it again.
I tried
global static $x;
but it doesn't work.
I need to know if I'm thinking in wrong way case I'm new to PHP.
<?php
$x = 5;
function myTest() {
echo "x is equal to".$GLOBALS['x']."";
$GLOBALS['x']++;
}
myTest();
myText();
?>
it executes only the first myTest().
and the second one display an error
Fatal error: Uncaught Error: Call to undefined function myText()
just declare it in global scope then use $GLOBALS[] array or global keyword to use that variable in a function. And as they hold the value even after function execution you don't need static keyword as well.
study $GLOBALS, Variable scope
you can use static or global to keep the value:
function doStuff() {
$x = null;
if ($x === null) {
$x = 'changed';
echo "changed.";
}
}
doStuff();
doStuff();
the result would be: changed.changed.
if you use:
function doStuff() {
static $x = null;
if ($x === null) {
$x = 'changed';
echo "changed.";
}
}
doStuff();
doStuff();
the result would be changed. because static keeps last value even if you call function in multi times
also global have the same result because of it's definition so you can also use:
global $x;
in the function and result would be same: changed.
You have typo problem in your code (second calling of your function):
function myTest() ....
Then you called it:
myTeXt();

Does the function run when assigned to local variable

Below is the example I put together to understand my confusion. Now my question is, when I make the function into a local variable, does it start to run instantly or does it wait for the local variable to be called.
//Here is the function
function myFunction(){
return 'Hello Stackoverflow';
}
//Does the functio run at this point
$stackoverflow = myFunction();
//Or does the function run here?
echo $stackoverflow;
You aren't making "the function into a local variable."
In your example the function runs, the string return value is assigned to $stackoverflow, then you echo the string.
I think you are trying to do this.
//Here is the function
function myFunction(){
return 'Hello Stackoverflow';
}
//Doesn't run yet
$stackoverflow = 'myFunction';
//This runs now
echo $stackoverflow();
You are not actually assigning a function to the variable, but the return value of the function.
And yes, the function is executed when you call it, i.e. when you assign it to the variable.
After that of course you have a variable with a value and you can do whatever you want with it.
It will run at the time of assignment:
$stackoverflow = myFunction();
You could assign the function to the variable if you want it called when referencing the variable and not when it's assigned:
$foo = function () {
return 'Hello Stackoverflow';
};
echo $foo();
The function run when it is assigned to a value, i.e, at $stackoverflow = myFunction();

How php parse and interpret function scope

Example 1: Here I expect that function hello must be in the global scope.
But as per my expectation it does not behave same.It does not put function hello into global scope. at run time php must put function hello into global scope. It says undefined function hello().
$fruit=true;
foo();
hello();
function foo()
{
echo "you are in the foo<br/>";
}
if($fruit)
{
function hello()
{
echo "you are in the hello<br/>";
}
}
Example 2 : Now as after example 1 , i supposed the below script must also work as example 1. i supposed it will give also error undefined function bar(). But now here it behave differently and execute bar.
foo();
bar();
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}
So i am unable to get the concept how php interpreter behave internally. How does it parse the program, and does it execute the step one by one , or whole program at once?
I quote a manual for you:
When a function is defined in a conditional manner .... Its definition must be processed prior to being called.
And more:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
Example One:
You do not define the function hello() until a part of the script has run, its in an IF and therefore does not get defined until after you attempt to call it
Like this you get no errors as the IF is run before the now defined funtion hello is called. And of corse either way it is in the GLOBAL scope. But your way it didnt exist anywhere until after you called it.
<?php
$fruit=true;
if($fruit)
{
function hello()
{
echo "you are in the hello<br/>";
}
}
foo();
hello();
function foo()
{
echo "you are in the foo<br/>";
}

PHP: Global variable scope

I have a separate file where I include variables with thier set value.
How can I make these variables global?
Ex. I have the value $myval in the values.php file. In the index.php I call a function which needs the $myval value.
If I add the include(values.php); in the beggining of the index.php file it looses scope inside the function. I will call the same variable in multiple functions in the index.php file.
Inside the function, use the global keyword or access the variable from the $GLOBALS[] array:
function myfunc() {
global $myvar;
}
Or, for better readability: use $GLOBALS[]. This makes it clear that you are accessing something at the global scope.
function myfunc() {
echo $GLOBALS['myvar'];
}
Finally though,
Whenever possible, avoid using the global variable to begin with and pass it instead as a parameter to the function:
function myfunc($myvar) {
echo $myvar . " (in a function)";
}
$myvar = "I'm global!";
myfunc($myvar);
// I'm global! (in a function)
Use inside your function :
global $myval;
PHP - Variable scope
Using the global keyword in the beginning of your function will bring those variables into scope. So for example
$outside_variable = "foo";
function my_function() {
global $outside_variable;
echo $outside_variable;
}
Is there a reason why you can't pass the variable into your function?
myFunction($myVariable)
{
//DO SOMETHING
}
It's a far better idea to pass variables rather than use globals.
Same as if you declared the variable in the same file.
function doSomething($arg1, $arg2) {
global $var1, $var2;
// do stuff here
}

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