Giving my function access to outside variable
By default, when you are inside a function, you do not have access to the outer variables.
If you want your function to have access to an outer variable, you have to declare it as global
, inside the function :
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
For more informations, see Variable scope.
But note that using global variables is not a good practice : with this, your function is not independant anymore.
A better idea would be to make your function return the result :
function someFuntion(){
$myArr = array(); // At first, you have an empty array
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
return $myArr;
}
And call the function like this :
$result = someFunction();
Your function could also take parameters, and even work on a parameter passed by reference :
function someFuntion(array & $myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
}
Then, call the function like this :
$myArr = array( ... );
someFunction($myArr); // The function will receive $myArr, and modify it
With this :
- Your function received the external array as a parameter
- And can modify it, as it's passed by reference.
- And it's better practice than using a global variable : your function is a unit, independant of any external code.
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
- Functions arguments
- Returning values
Access variable from function inside of nested function
You have two options:
Give $content
as a parameter
function foo() {
$content = 'foobar';
function bar($content) {
echo $content; // echos something
}
}
Take $content
outside of the function and use global there.
$content = '';
function foo() {
global $content;
$content .= 'foobar';
function bar($content) {
global $content;
echo $content; // echos something
}
}
Access a variable inside a function which is inside a function in javascript?
Thanks.
I declared the variable as global and inserted value inside the inner function and then made a function call inside the function to trigger another function which call the value.
var a=0;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
success: function(count) {a =count; total();},
error:function(error){}
});
function total(){alert (a);}
Access a function variable outside the function without using global
You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):
def hi():
# other code...
hi.bye = 42 # Create function attribute.
sigh = 10
hi()
print(hi.bye) # -> 42
Functions are objects in Python and can have arbitrary attributes assigned to them.
If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this
argument to each call to the decorated function.
This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self
— I picked something different to avoid confusion, but like the self
argument, it can be named whatever you wish.
Here's an example of that approach:
def add_this_arg(func):
def wrapped(*args, **kwargs):
return func(wrapped, *args, **kwargs)
return wrapped
@add_this_arg
def hi(this, that):
# other code...
this.bye = 2 * that # Create function attribute.
sigh = 10
hi(21)
print(hi.bye) # -> 42
Note
This doesn't work for class methods. Just use the instance argument, named self
by convention, that's already passed to methods instead of the method's name. You can reference class-level attributes through type(self)
. See Function's attributes when in a class.
Access local variable in function from outside function (PHP)
Its not possible. If $variable
is a global variable you could have access it by global
keyword. But this is in a function. So you can not access it.
It can be achieved by setting a global variable by$GLOBALS
array though. But again, you are utilizing the global context.
function outside() {
$GLOBALS['variable'] = 'some value';
inside();
}
function inside() {
global $variable;
echo $variable;
}
Access variable from a different function from another file
You can access the value of a variable in a function by 1) returning the value in the function, 2) use a global variable in the module, or 3) define a class.
If only want to access a single variable local to a function then the function should return that value. A benefit of the class definition is that you may define as many variables as you need to access.
1. Return value
def champs_info(champname:str, tier_str:int):
...
tier = tier_access.text
return tier
2. global
tier = None
def champs_info(champname:str, tier_str:int):
global tier
...
tier = tier_access.text
Global tier vairable is accessed.
from mypythonlib import myfunctions
def test_champs_info():
myfunctions.champs_info("abomination", 6)
return myfunctions.tier
print(test_champs_info())
3. class definition:
class Champ:
def __init__(self):
self.tier = None
def champs_info(self, champname:str, tier_str:int):
...
self.tier = tier_access.text
test_functions.py can call champs_info() in this manner.
from mypythonlib import myfunctions
def test_champs_info():
info = myfunctions.Champ()
info.champs_info("abomination", 6)
return info.tier
print(test_champs_info())
Access variable from outside function (PHP)
Insert this inside the function:
global $ERROR;
So, the variable can be accessed inside the function scope (see global keyword).
function validateLogin($data) {
global $ERROR;
...
}
Alternatively you can access to all variables that are outside the function using $GLOBALS:
$GLOBALS['ERROR']
access variables outside function
Use return $v
:
function ($form, $db) {
$v = count($a);
return $v;
}
<script type="text/javascript">
$(document).ready(function() {
for ($i=0; $i< <?php echo function( $form , $db )-1; ?>; $i++) {//here
}
python giving NameError with global variable
In python, the variable has three scopes: local, nonlocal and global.
- A variable in a function, the variable's scope is local.
- A variable outside of a function, the variable's scope is global.
- For nested functions, if a variable is in the outer function, its scope is nonlocal for the inner function. If the inner function wants to access the variable in the outer function, need to use
nonlocal
keyword.
So, change global cnt
to nonlocal cnt
, the code will be work.
This document may help you understand variable scopes in python:
Python Scope of Variables
Related Topics
PHP Elvis Operator VS Null Coalescing Operator
Recursive Function to Generate Multidimensional Array from Database Result
Best Way to Get Result Count Before Limit Was Applied
Detecting Request Type in PHP (Get, Post, Put or Delete)
Getting Raw SQL Query String from Pdo Prepared Statements
PHP: How to Determine Every Nth Iteration of a Loop
Simplest Two-Way Encryption Using PHP
How to Remove "Index.PHP" in Codeigniter'S Path
How to Encrypt/Decrypt Data in PHP
PHP 7.2 Function Create_Function() Is Deprecated
Preferred Method to Store PHP Arrays (Json_Encode VS Serialize)