I am trying to access $my_var from within a function, I know I can use a global $my_var to do so, but that IMO isn't a good way to do this since if $my_var is outside of the call_user_func it will use that one instead of the one within. I can't use use since the function isn't an anonymous function.
Is there a good way to do this without using a class?
call_user_func(function(){
$my_var = null;
function myFunc($value1, callable $callback){
// Access $my_var
}
});
myFunc('value 1', function(){});
There are several ways. The simplest is to simply pass $var as a parameter, and update it through the function's return value:
$var = null;
function foo( $var ) { $var++; }
$var = foo( $var );
Another way is to declare the parameter as a reference (& $var):
$var = null;
function foo( & $var ) { $var++; }
foo( $var );
A third way is to use an anonymous function and specify the use of the variable:
$var = null;
$foo = function() use( & $var ) { $var++; }
$foo();
Related
When using anonymous functions in PHP, you can easily use variables from right outside of its scope by using the use() keyword.
In my case the anonymous functions are already defined somewhere, but called later on (somewhere else) in a class.
The following piece of code is to illustrate the idea:
<?php
$bla = function ( $var1 ) use ($arg)
{
echo $var1;
};
class MyClass
{
private $func;
public function __construct ( $func )
{
$this->func = $func;
}
public function test ( $arg )
{
$closure = $this->func;
$closure ( 'anon func' );
}
}
$c = new MyClass($bla);
$c->test ( 'anon func' );
What i'm doing is i create an anonymous function and store that in a variable. I pass that variable to the method of a class and that is where i want to run the anonymous function.
But i can't use the use() keyword to get the $arg parameter from the method this way. Because the anonymous function was declared outside of the method.
But i really need a way to get the variables from the method where the anonymous function is run from. Is there a way to do that, when the anonymous function is declared somewhere else..?
The point of the use keyword is to inherit/close over a particular environment state from the parent scope into the Closure when it's defined, e.g.
$foo = 1;
$fn = function() use ($foo) {
return $foo;
};
$foo = 2;
echo $fn(); // gives 1
If you want $foo to be closed over at a later point, either define the closure later or, if you want $foo to be always the current value (2), pass $foo as a regular parameter.
FWIW, you can do it if you use a use reference (php.net ex 3.3) and a global, ugly since it uses globals, but just to put it out there:
<?php
$bla = function ( $var1 ) use (&$arg)
{
return "var1:$var1, arg:$arg";
};
class MyClass
{
private $func;
public function __construct ( $func )
{
$this->func = $func;
}
public function test ( $param )
{
global $arg;
$arg=$param;
$closure = $this->func;
return $closure ( 'anon func' );
}
}
$c = new MyClass($bla);
echo $c->test ( 'bla bla' ); //var1:anon func, arg:bla bla
When using anonymous functions in PHP, you can easily use variables from right outside of its scope by using the use() keyword.
In my case the anonymous functions are already defined somewhere, but called later on (somewhere else) in a class.
The following piece of code is to illustrate the idea:
<?php
$bla = function ( $var1 ) use ($arg)
{
echo $var1;
};
class MyClass
{
private $func;
public function __construct ( $func )
{
$this->func = $func;
}
public function test ( $arg )
{
$closure = $this->func;
$closure ( 'anon func' );
}
}
$c = new MyClass($bla);
$c->test ( 'anon func' );
What i'm doing is i create an anonymous function and store that in a variable. I pass that variable to the method of a class and that is where i want to run the anonymous function.
But i can't use the use() keyword to get the $arg parameter from the method this way. Because the anonymous function was declared outside of the method.
But i really need a way to get the variables from the method where the anonymous function is run from. Is there a way to do that, when the anonymous function is declared somewhere else..?
The point of the use keyword is to inherit/close over a particular environment state from the parent scope into the Closure when it's defined, e.g.
$foo = 1;
$fn = function() use ($foo) {
return $foo;
};
$foo = 2;
echo $fn(); // gives 1
If you want $foo to be closed over at a later point, either define the closure later or, if you want $foo to be always the current value (2), pass $foo as a regular parameter.
FWIW, you can do it if you use a use reference (php.net ex 3.3) and a global, ugly since it uses globals, but just to put it out there:
<?php
$bla = function ( $var1 ) use (&$arg)
{
return "var1:$var1, arg:$arg";
};
class MyClass
{
private $func;
public function __construct ( $func )
{
$this->func = $func;
}
public function test ( $param )
{
global $arg;
$arg=$param;
$closure = $this->func;
return $closure ( 'anon func' );
}
}
$c = new MyClass($bla);
echo $c->test ( 'bla bla' ); //var1:anon func, arg:bla bla
I was wondering if it's possible to change and initialize variables in a function without passing arguments to the function. Here is what I want to achieve:
$foo = 'Lorem';
$array = array();
foobar($foo);
function foobar(){
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
fubar();
function fubar(){
if (empty($fouten))
echo $bar;
}
$foo is a local (uninitialized) variable inside a function. It is different from the global variable $foo ($GLOBALS['foo']).
You have two ways:
$foo;
$bar;
$array = array();
function foobar(){
global $foo, $array, $bar;
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
or by using the $GLOBAL array …
This is not really good practice though and will become a maintenance nightmare with all those side effects
Functions in php can be given arguments that have default values. The code you posted as written will give you notices for undefined variables. Instead, you could write:
function foobar($foo = null) {
if($foo) { // a value was passed in for $foo
}
else { // foo is null, no value provided
}
}
Using this function, neither of the below lines will produce a notice
foobar();
foobar('test');
I am trying to change a variable that is outside of a function, from within a function. Because if the date that the function is checking is over a certain amount I need it to change the year for the date in the beginning of the code.
$var = "01-01-10";
function checkdate(){
if("Condition"){
$var = "01-01-11";
}
}
A. Use the global keyword to import from the application scope.
$var = "01-01-10";
function checkdate(){
global $var;
if("Condition"){
$var = "01-01-11";
}
}
checkdate();
B. Use the $GLOBALS array.
$var = "01-01-10";
function checkdate(){
if("Condition"){
$GLOBALS['var'] = "01-01-11";
}
}
checkdate();
C. Pass the variable by reference.
$var = "01-01-10";
function checkdate(&$funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate($var);
Just use the global keyword like so:
$var = "01-01-10";
function checkdate(){
global $var;
if("Condition"){
$var = "01-01-11";
}
}
Any reference to that variable will be to the global one then.
All the answers here are good, but... are you sure you want to do this?
Changing global variables from within functions is generally a bad idea, because it can very easily cause spaghetti code to happen, wherein variables are being changed all over the system, functions are interdependent on each other, etc. It's a real mess.
Please allow me to suggest a few alternatives:
1) Object-oriented programming
2) Having the function return a value, which is assigned by the caller.
e.g. $var = checkdate();
3) Having the value stored in an array that is passed into the function by reference
function checkdate(&$values) {
if (condition) {
$values["date"] = "01-01-11";
}
}
Hope this helps.
Try this pass by reference
$var = "01-01-10";
function checkdate(&$funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate($var);
or Try this same as the above, keeping the function as same.
$var = "01-01-10";
function checkdate($funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate(&$var);
I know I can use $GLOBALS['var'] inside a function to refer to variables in the global scope.
Is there anyway I can use some kind of a declaration inside the function so I will be able to use $var without having to use $GLOBAL['var'] every time?
Joel
Although it's not recommended, but if you do want to, here's what you can do:
If you only want to GET the values from the vars (and not SET the values), just use extract:
extract($GLOBALS);
This will extract and create all the variables in the current scope.
How about using static class?
such as
class example
{
public static $global;
public static function set($arr)
{
foreach ($arr as $key=>$val)
{
self::$global[$key] = $val;
}
}
}
function example_function()
{
var_dump( example::$global );
}
example::set( array('a'=>1, 'b'=>2) );
example_function();
You can use the global keyword, So you can use type $var instead of $GLOBALS['var'] inside a function.
function myFunc() {
global $var;
$var = 3;
}
$var = 1;
myFunc();
echo $var;
Output: 3