Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable defined outside callback function is unaccessible inside the function [duplicate]

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

?>
like image 826
Alexander Beninski Avatar asked Jan 17 '26 04:01

Alexander Beninski


2 Answers

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);
like image 125
Bartosz Grzybowski Avatar answered Jan 19 '26 17:01

Bartosz Grzybowski


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);
like image 41
Jeremy Avatar answered Jan 19 '26 19:01

Jeremy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!