I am passing a parameter, "action", to another file, process.php. The value of "action" will be the name of a function that is defined within process.php. If the function exists, it should be called automatically. I tried the following:
$action = $_REQUEST['action'];
$function = {$action}();
if(function_exists($function))
$function;
else
die('No function.');
That, however, does not work. Any suggestions? Thanks!
As #Positive said you are calling the function on assignment. I just wanted to add a few things - this is a bit risky - what if the request contents were 'phpinfo' or something even more dangerous. Perhaps a better idea would be to select the function from an array of allowed functions:
$allowed_functions = array(
'my_function_one',
'my_function_two'
);
$action = $_REQUEST['action'];
if(in_array($action,$allowed_functions)){
{$action}();
}
else {
die('No function.');
}
Change the assignment to $function like below. Note that function_exists only take the function name.
$action = $_REQUEST['action'];
$function = $action;
Actually you are calling the function with this statment $result = $function();, see Variable functionsPHP-Manual.
and also sanitize the GET parameter according to your function name conventions.
Related
I'm refactoring all the codes given to me and I saw in the code that the're so many repeated variables that is using with other methods
which is this
$tag_id = json_decode($_POST['tag_id']);
$tag_name = json_decode($_POST['tag_name']);
$pname = json_decode($_POST['pname']);
$icode = json_decode($_POST['icode']);
$bname = json_decode($_POST['bname']);
$client = json_decode($_POST['client']);
$package = json_decode($_POST['package']);
$reference = json_decode($_POST['reference']);
$prodcat = json_decode($_POST['prodcat']);
$physical_array = json_decode($_POST['physical_array']);
$chemical_array = json_decode($_POST['chemical_array']);
$physpec_array = json_decode($_POST['physpec_array']);
$micro_array = json_decode($_POST['micro_array']);
$microspec_array = json_decode($_POST['microspec_array']);
$prod_type = json_decode($_POST['prod_type']);
$create_physical_id_array = json_decode($_POST['create_physical_id_array']);
$create_chemical_id_array = json_decode($_POST['create_chemical_id_array']);
$create_micro_id_array = json_decode($_POST['create_micro_id_array']);
my question is how can i just use put it in one method and i'll just call it to other methods instead of repeating that code.
thank you
You can't call it from other methods. Because the variables defined to that method are local. Instead you can define the variables as member variables of that class and access from any method or even from outside class depending upon the access specifier.
protected $a=2;
public function method1()
{
echo $this->a;
}
public function method2()
{
echo $this->a;
}
Put it in an array
$post_array = [];
foreach($_POST as $key => $value)
{
$post_array[$key] = json_decode($value);
}
return $post_array;
and then call it like this
$post_array['create_micro_id_array'];
Since it appears you are very much aware of the variable names you want to use... I'll suggest PHP Variable variables
To do this, you can loop through your $_POST and process the value while using the key as variable name.
foreach($_POST as $key => $value)
{
$$key = json_decode($value);
}
At the end of the day, these 4 lines would generate all that... However i'm not so sure of how friendly it may appear to someone else looking at the code. Give it a shot.
You may try extract function.
extract($_POST);
I'm having troubles with variables inside functions and being able to read them in a index.php. Let's say I have this function (functions.php):
function firstFunction(){
$id = '1234';
secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber = 1234 ){
$name = "James"; //should say "james".
}
and in the index.php have something like that:
include(functions.php)
<?php
firstFunction();
echo $name;
?>
does anyone know a possible way to do this?, i need to be a able to read from a variable inside a function that is in another function.
Also when calling a function inside a function allow this to read a variable from the first function.
Thanks.
Variables created inside a function are local to it, you can't read their contents outside of it (because all function-local variables get deleted after the function finished running).
The improper way would be to make the $name variable global in the second function.
A better way to do it would be to use function return values: secondFunction returns $name, and firstFunction returns whatever it gets from calling secondFunction($id).
Oh, and by the way, you have another logical error in your secondFunction: Your if test will not behave like you probably intended because you are using a variable value assignment operator (=) instead of comparison (==) which always succeeds returns the assigned value that evaluates to a "true" value in most (but not all) cases.
This is very bad practice - using globals. The answer you need is:
global $name;
You need to put it above the row:
$name = "James"; //should say "james".
You declare $name inside second function, so it only exists there (that is it's "Scope").
To use it's value you need the functions to return it:
function secondFunction($idnumber){
if ( $idnumber == 1234 ){
$name = "James"; //should say "james".
}
else {
$name = "";
}
return $name;
}
function firstFunction(){
$id = 1234;
return secondFunction($id);
}
and in the index.php have something like that:
<?php
include 'functions.php';
$name = firstFunction();
echo $name;
?>
You can't call a variable like that it is out of scope what you need to do is as follows
function firstFunction(){
$id = '1234';
return secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber == 1234 ){
return "James";
}
}
Then in your index do this
<?php
include(functions.php);
echo firstFunction();
?>
A variable that is out of scope can not be accessed for example if you defined a variable inside a if statement is would only be able to be used in that statement and it is the same with the functions and variables that are inside. Thought I needed to explain my answer more.
Try this...
index.php
<?php
// Includes
include("functions.php");
// Create a variable to store the output of your function
$returned_name = firstFunction();
// Echo the variable
echo "Name: " . $returned_name;
?>
functions.php
<?php
// Function 1
function firstFunction() {
$id = "1234";
return secondFunction($id);
}
// Function 2
function secondFunction($idnumber) {
if ($idnumber == "1234") {
$name = "James";
} else if ($idnumber == "5678") {
$name = "Brian";
}
return $name;
}
?>
I have a function that uses its own params but also checks if any get/post values are avaliabe for different behavior.
I'd like to be able to do that in the home page, which url is: domain.com/
For example:
function simulate_get($name,$val){
// do it
}
And then, in code
..
simulate('foo','last_posts');
show_user_posts($user,$bla,$ble);
..
I know that I should add an extra paramerter to the function but still wondering if is actually posible in PHP to do that.
Just write to it:
function simulate_get($name, $val)
{
$_GET[$name] = $val;
}
As $_GET is a superglobal you can just do:
$_GET['foo'] = 'last_posts';
and then directly use it in your code:
$_GET['foo'] = 'last_posts';
show_user_posts($user,$bla,$ble);
or if you want to use a function to set it:
function simulate_get ($key, $value) {
$_GET[$key] = $value;
}
simulate_get('foo','last_posts');
show_user_posts($user,$bla,$ble);
Just change the contents of $_GET, that's no problem at all.
$_GET['foo'] = 'last_posts';
I have a function variable like this...
$aName = "My Name";
The function need to pass in like this:
$sayHelloFunction = function sayHello($aName){
echo($aName);
}
Than, I have a method that responsible for execute the sayHelloFunction:
runningFunction($sayHelloFunction($aName));
in the runningFunction, it will have some condition to execute the function, but when I pass the "$sayHelloFunction($aName)" to runningFunction, it execute automatically, but I would like to pass the variable $aName as well, how can I achieve it? Thank you.
runningFunction($sayHelloFunction, $aName);
Simples.
You will have to pass the arguments separately. However, you could wrap them in an array so that you can pass them to runningFunction as a single argument, like this:
$printFunction = function($args) {
print $args['lastname'].', '.$args['firstname'];
};
function runningFunction($f, $a) {
$f($a);
}
$firstname = 'Bob';
$lastname = 'Smith';
$functionArguments = array(
'firstname' => $firstname,
'lastname' => $lastname
);
runningFunction($printFunction, $functionArguments);
If you want your dynamic functions to get "proper" arguments, then I see no way around something like this:
function runningFunction($f, $a) {
switch(count($a)) {
0: $f(); break;
1: $f($a[0]); break;
2: $f($a[0], $a[1]); break;
3: $f($a[0], $a[1], $a[2]); break;
// and so on
}
}
Pass the parameters as an array, and then use call_user_func_array() to call your function.
This way your runningFunction() will be absolutely abstract (as you requested), it can call any type of function, it's your responsibility to pass the right number of parameters.
function runningFunction ($callback, $parameters=array()) {
call_user_func_array($callback, $parameters);
}
runningFunction($sayHelloFunction, array($aName));
call_user_func_array()
as xconspirisist suggested pass $aName as a seperate parameter to the function.
Details on Variable Functions can be found on the PHP site.
Use an anonymous function when calling runningFunction
function runningFunction($func) {
$func();
}
runningFunction(function() {
$sayHelloFunction($aName));
// You can do more function calls here...
});
I have a function variable like this...
$aName = "My Name";
$sayHelloFunction = public function sayHello($aName){
echo($aName);
}
and I have something like this.....
callAFunctionFromFunction($sayHelloFunction);
Inside the "callAFunctionFromFunction", I do this:
if(is_callable($sayHelloFunction)) {
$sayHelloFunction();
}
I found that the "My Name" can't display, what did I do wrong...
I suggest you to look here and here as these exact threads deal with passing a function as a parameter. Also closures (anonymous functions) in PHP have no name (that's why they are called anonymous), so what you should do is something like that.
<?php $sayHelloFunction = function($aName){
echo($aName);
};
if(is_callable($sayHelloFunction)) $sayHelloFunction("Testing 1,2,3");
The function sayHello expects a parameter $aName, but when you call it you don't pass in a value.
You would need to do this:
if(is_callable($sayHelloFunction)) {
$sayHelloFunction("Hello John");
}
Also you can't use the public access type with closures.
$sayHelloFunction = function sayHello($aName) {
echo($aName);
}