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.
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:
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:
PHP take string and check if that string exists as a variable
(3 answers)
Closed 8 years ago.
I have a field that depends has custom text if a certain condition is met...and if it isn't the field is blank.
I have written a custom function test if a variable is set
function AmISet($fieldName) {
if (isset($fieldName)) {
echo "I am set";
}else{
echo "I am not set";
}
};
but when I attach it the field I get an error that the variable is undefined. But when I do a regular isset($fieldName);
I don't have a problem. Is there any way to get around this and have my function do this instead of the isset()?
I want to add other logic in the function but I only want it to work if the variable is set...but I don't want the undefined error if it is not.
I am new to php and really appreciate any help or direction you can give me.
Thank you for the help!
You need to pass the variable by reference:
function AmISet(&$fieldName) {
if (isset($fieldName)) {
echo "I am set\n";
} else {
echo "I am not set\n";
}
}
Test cases:
$fieldName = 'foo';
AmISet($fieldName); // I am set
unset($fieldName);
AmISet($fieldName); // I am not set
However, this function is not useful as it is, because it will only output a string. You can create a function that accepts a variable and return if it exists (from this post):
function issetor(&$var, $default = false) {
return isset($var) ? $var : $default;
}
Now it can be used like so:
echo issetor($fieldName); // If $fieldName exists, it will be printed
the $fieldName comes from a query that is performed when a checkbox
is checked. If the box is checked the query is made and the variable
is set from the query, if not it doesn't exist and the field is blank.
Filter functions are designed for this kind of tasks:
<input type="foo" value="1">
$foo = filter_input(INPUT_POST, 'foo')==='1';
(There's also a specific FILTER_VALIDATE_BOOLEAN filter you can pass as second argument.)
And now you have a pure PHP boolean that always exists.
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)
{
}
This question already has answers here:
passing POST array to php function
(3 answers)
Closed 9 years ago.
I've been working on a project for a game (so you'll understand that I can't post the actual script), and I'm cleaning up the code and placing code into functions instead of just after the
if ($_POST['name'] { //code }
Is this the correct method of doing what I'm trying? (I tried, but it broke my system)
if ($_POST['action'] == "actionName") actionName($_POST); //calls function if the $_POST is present
function actionName($_POST) { //code }
Thanks in advance for correct answers!
$_POST is globally accessible. So you don't have to pass to your function:
if ($_POST['action'] == 'actionName') actionName();
function actionName() {
//code using $_POST
}
If you want your function to be able to do what it wants with any array (i.e. other than $_POST), then make the function take a parameter, but don't call it $_POST:
if ($_POST['action'] == 'actionName') actionName($_POST);
function actionName(parameters) {
//code using parameters
}
$_POST is a super-global. All PHP code, no matter the scope, automatically has access to this data structure.
Therefore, the following is fine:
if ($_POST['action'] == "actionName") {
actionName();
}
and then
function actionName() {
print_r($_POST);
// code
}
$_POST is already a superglobal variable so you do not need to pass it to a function. If the function needs the content of $_POST then make a copy and pass it to the function.
However, from your example, it seems to me that you need to pass $_POST['action'] to your function instead of $_POST.
Well in your example you need to have quotes around your string variables:
//calls function if the $_POST is present
if ($_POST['action'] == 'actionName') actionName($_POST);
function actionName($_POST) { /*code*/ }
Although $_POST is super-global, yes of course you can do that and is actually a good idea. This way you decouple your code and maybe you can reuse actionName in another part of the application.
However, don't name the parameter of the function $_POST (this is more confusing than helpful).
To avoid a bunch of if statements for every possible action, have a look at call_user_func [docs].
E.g. you could do:
$allowed_actions = array_fill_keys(array('actionName', ...), true);
if(isset($allowed_actions[$_POST['action']])) {
call_user_func($_POST['action'], $_POST);
}
You should move the function before the code that executes it along with what everyone else here is saying about the $_POST array. Try this if you want
function actionName($input) { // code and return }
if (isset($_POST['action'])) {
$action = $_POST['action'];
if ($action == 'actionName') {
$name = actionName($action);
}
}
$_POST is a super global (as other have mentioned), so you don't need to pass it in.
You can pass it in so that you decouple the function code from the environment in which it's running. For example, should you wish to initiate such an action as a result of something else in the code, you can pass in an array with the same key/values that $_POST would have to do so
If you do pass in $_POST to a function, name the function argument something else, hopefully something that indicates what the data represents
Consider that the function may not need all the key/values that $_POST normally contains, and if you might be better off defining a function that takes only the arguments it needs in order to function
If you are talking about dynamically calling a function, you could achieve it this way:
/*
Example Post
$_POST['functionName'] = 'doSomething';
$_POST['value'] = 'woot!';
*/
function doSomething($message) {
echo $message;
}
// Call the function if it exists
if (function_exists($_POST['functionName']) {
call_user_func($_POST['functionName'], $_POST['value']);
}
// The above would output "Woot!"