Access local variable in function from outside function (PHP) - php

Is there a way to achieve the following in PHP, or is it simply not allowed? (See commented line below)
function outside() {
$variable = 'some value';
inside();
}
function inside() {
// is it possible to access $variable here without passing it as an argument?
}

note that using the global keyword is not advisable, as you have no control (you never know where else in your app the variable is used and altered). but if you are using classes, it'll make things a lot easier!
class myClass {
var $myVar = 'some value';
function inside() {
$this->myVar = 'anothervalue';
$this->outside(); // echoes 'anothervalue'
}
function outside() {
echo $this->myVar; // anothervalue
}
}

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;
}

No, you cannot access the local variable of a function from another function, without passing it as an argument.
You can use global variables for this, but then the variable wouldn't remain local.

It's not possible. You can do it by using global. if you just only do not want to define the parameters but could give it inside the function you can use:
function outside() {
$variable = 'some value';
inside(1,2,3);
}
function inside() {
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
for that see the php manual funct_get_args()

You cannot access the local variable in function. Variable have to set as global
function outside() {
global $variable;
$variable = 'some value';
inside();
}
function inside() {
global $variable;
echo $variable;
}
This works

Related

How to access PHP variable on every part of a wordpress page? [duplicate]

I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}

PHP use variable defined outside of function [duplicate]

I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}

How to use class function variable within a local function

I'm working on a WordPress shortcode plugin, so I need to define a function to use with add_action('wp_footer', 'fnc_name') for example. I have created the plugin as a class with public functions and static variables.
Here's an example of what I'm trying to do (use $count in the local function tryToGetIt):
class Test {
public static $count;
public function now () {
if (!$this::$count) {
$this::$count = 0;
}
$this::$count++;
$count = (string) $this::$count;
echo 'count should be '.$count;
function tryToGetIt() {
global $count;
echo 'count is '.$count;
}
tryToGetIt();
}
};
$test = new Test();
$test->now();
You can see the demo on IDEONE: http://ideone.com/JMGIFr
The output is 'count should be 1 count is ';
As you can see I've tried declaring the $count variable with global to use the variable from the outer function, but that is not working. I've also tried $self = clone $this and using global $self within the local function.
How can the local function use the variables from within the class's public function?
This is not possible with global. PHP has exactly two variable scopes: global, and local.
<?php
$foo = 'bar'; // global scope <-----------
\
function x() { |
$foo = 'baz'; // function local scope |
|
function y() { |
global $foo; // access global scope /
echo $foo;
}
y();
}
x(); // outputs 'bar'
You COULD try a closure, e.g.
function foo() {
$foo = 'bar';
$baz = function() use (&$foo) { ... }
}
There is no practical way to access a scope defined at some intermediate level of a function call chain. You only ever have the local/current scope, and the global scope.
You could do:
function tryToGetIt($count) {
echo 'count is '.$count;
}
tryToGetIt($count);
Or to select the static variable use:
Test::$count within the tryToGetIt() function.
I tried this code, which works
class Test {
public static $count;
public function now () {
if (!$this::$count) {
$this::$count = 0;
}
$this::$count++;
$count = (string) $this::$count;
echo 'count should be '.$count;
function tryToGetIt() {
echo 'count is '. Test::$count;
}
tryToGetIt();
}
};
$test = new Test();
$test->now();
But I'm not sure I understand why you are trying to do this. Why not make tryToGetIt() a private function within Test rather than nested within now()?

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.

Make $_GET variable available within function scope

How to pass a $_GET variable into function?
$_GET['TEST']='some word';
public function example() {
//pass $_GET['TEST'] into here
}
When I try to access $_GET['TEST'] in my function, it is empty.
The $_GET array is one of PHPs superglobals so you can use it as-is within the function:
public function example() {
print $_GET['TEST'];
}
In general, you pass a variable (argument) like so:
public function example($arg1) {
print $arg1;
}
example($myNonGlobalVar);
If this is a function and not an object method then you pass the parameter like so
function example($test) {
echo $test;
}
and then you call that function like so
$_GET['test'] = 'test';
example($_GET['test']);
output being
test
However if this is an object you could do this
class Test {
public function example($test) {
echo $test;
}
}
and you would then call it like so
$_GET['test'] = 'test';
$testObj = new Test;
$testObj->example($_GET['test']);
and the output should be
test
I hope this helps you out.
First of all - you should not set anything to superglobals ($_GET, $_POST, etc).
So we convert it to:
$test = 'some word';
And if you want to pass it to the function just do something like:
function example($value) {
echo $value;
}
And call this function with:
example($test);
function example ($value) {
$value; // available here
}
example($_GET['TEST']);
function example($parameter)
{
do something with $parameter;
}
$variable = 'some word';
example($variable);
Simply declare the value for the variable by
declare the function by
function employee($name,$email) {
// function statements
}
$name = $_GET["name"];
$email = $_GET["email"];
calling the function by
employee($name,$email);

Categories