This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
This is really simple but I can't get my head around it. I am setting a datestamp and would like to be able to use it inside a function like this..
$date_stamp = date("dmy",time());
function myfunction() {
echo $date_stamp;
}
This is not working and $date_stamp is not available inside the function, how can I use this?
This is basic PHP. $date_stamp is out of scope within your function. To be in scope you must pass it as a parameter:
$date_stamp = date("dmy",time());
function myfunction($date) {
echo $date;
}
// call function
myfunction($date_stamp);
See PHP variable scope.
Just as an add-on to John Conde's answer, you can also use a closure like so
<?php
$date_stamp = date("dmy",time());
$myfunction = function() use ($date_stamp) {
echo '$myfunction: date is '. $date_stamp;
};
$myfunction();
Related
This question already has answers here:
PHP, an odd variable scope?
(6 answers)
Closed 11 months ago.
I have this piece of code:
$exists = false;
foreach ($outsiderTests as $key => $outsiderTest) {
$textExists = null;
foreach ($tests as $test) {
if ($outsiderTest->getName() == $test->getName()) {
$exists = true;
$existingTest = $test;
break;
} else
$exists = false;
}
var_dump($existingTest, $test);
}
As you can see, I want to see if there is an equivalent to an outsiderTest in $tests array. I thought I would have to save the existing equivalent $test on another variable as it would be gone after the foreach ends, but it does not.
The value of $existingTest and $test is the same when I dump them. This is cool, and makes me able to get rid of the mentioned $existingTest variable, but makes me wonder if I am understanding PHP's loop functionality.
Doesn't the $test variable only exist inside the foreach scope? Does PHP temporarily save the value of the last index the execution has run through?
PHP's variable scope is explained here: https://www.php.net/manual/en/language.variables.scope.php
Effectively you have 2 scopes:
The global scope
The local function scope
So a loop variable will be accessible out of it's scope and will contain the last value it had. This is why you got this behaviour.
If you have a loop calling a function then you have multiple options:
Declare the external variable with the global keyword inside the function.
Access globals with the $GLOBALS variable.
Pass the globals you need to your anonymous function with the use () syntax.
This question already has answers here:
Are PHP Variables passed by value or by reference?
(16 answers)
How to declare a global variable in php?
(10 answers)
Closed 3 years ago.
I would like to be able to assign the name of a variable outside the function so that the function can assign the chosen variable. It does not seem to work. Anyone have any ideas?
Below is my attempt, however the $admin variable is empty after running the function.
function assign_check($variable, $check) {
if (empty($_POST[$check])) {
$variable = "no";
} else {
$variable = $_POST[$check];
}
}
assign_check('$admin', 'admin');
My question is not about the use of global variables.
You can request a reference in the function body.
function assign_check(&$variable, $check) {
$variable = 'hello';
}
And call passing a variable (reference).
assign_check($admin, 'admin');
$admin value is now 'hello';
Fitting that to your code would result in
function assign_check(&$variable, $check) {
$variable = empty($_POST[$check]) ? "no" : $_POST[$check];
}
assign_check($admin', 'admin');
But returning a proper value would be much cleaner code than using references. Using a ternary operator like presented above would it even simplify without need of a function at all.
A normal way to assign the result of a function to a variable name specified outside the function would be to have the function return the result and assign it directly to the variable when you call the function.
function assign_check($check) {
if (empty($_POST[$check])) {
return "no";
} else {
return $_POST[$check];
}
}
$admin = assign_check('admin');
I would do it this way unless there was a compelling reason to do it otherwise.
For the specific type of thing it looks like this function is intended to do, I would suggest looking at filter_input.
This question already has answers here:
How to call a function from a string stored in a variable?
(18 answers)
Closed 1 year ago.
I found question from here. But I need to call function name with argument.
I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:
function foo ($argument)
{
//code here
}
function bar ($argument)
{
//code here
}
$functionName = "foo";
$functionName($argument);//Call here foo function with argument
// i need to call the function based on what is $functionName
Anyhelp would be appreciate.
Wow one doesn't expect such a question from a user with 4 golds. Your code already works
<?php
function foo ($argument)
{
echo $argument;
}
function bar ($argument)
{
//code here
}
$functionName = "foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)
?>
Output
Joke
Fiddle
Now on to a bit of theory, such functions are called Variable Functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
If you want to call a function dynamically with argument then you can try like this :
function foo ($argument)
{
//code here
}
call_user_func('foo', "argument"); // php library funtion
Hope it helps you.
you can use the php function call_user_func.
function foo($argument)
{
echo $argument;
}
$functionName = "foo";
$argument = "bar";
call_user_func($functionName, $argument);
if you are in a class, you can use call_user_func_array:
//pass as first parameter an array with the object, in this case the class itself ($this) and the function name
call_user_func_array(array($this, $functionName), array($argument1, $argument2));
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 8 years ago.
What does "&" mean in '&$var' in PHP? Can someone help me to explain this further. Thank you in advance.
It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.
function passByReference(&$test) {
$test = "Changed!";
}
function passByValue($test) {
$test = "a change here will not affect the original variable";
}
$test = 'Unchanged';
echo $test . PHP_EOL;
passByValue($test);
echo $test . PHP_EOL;
passByReference($test);
echo $test . PHP_EOL;
Output:
Unchanged
Unchanged
Changed!
You can pass a variable to a function by reference. This function will be able to modify the original variable.
You can define the passage by reference in the function definition with &
for example..
<?php
function changeValue(&$var)
{
$var++;
}
$result=5;
changeValue($result);
echo $result; // $result is 6 here
?>
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend
an ampersand (&) to the argument name in the function definition.
This question already has answers here:
Can't access global variable inside function
(5 answers)
Closed 9 years ago.
i need to access a variable which is declared in another php file within a function.. How can i do it?
a.php
<?php
$global['words']=array("one","two","three");
echo "welcome"
?>
b.php
<?php
$words = $global['words'];
require_once('a.php');
print_r($global['words']);
function fun()
{
print_r($global['words']); // not displaying here
}
fun();
?>
now i am able to access the "$global['words']" variable in b.php file, but not within function, how can i make it visible inside the function?
The preferred option is to pass as a parameter:
function fun($local) {
print_r($local['words']);
}
fun($global);
If for some reason you can't use that approach, then you can declare the variable as global:
function fun() {
global $global;
print_r($global['words']);
}
fun();
Or use the $GLOBALS array:
function fun() {
print_r($GLOBALS['global']['words']);
}
fun();
But in general, using global variables is considered bad practise.
actually your function does n't know about anything outside it, if it's not a classes, or global php vars such as $_POST , you can try to define function as:
function fun() use ($globals)
{
}