i have below a function called test thats being called, and just echos "test" keeping it simple, for this question.
test();
function test() {
echo "do something";
}
However i want to try and make the function dynamic if thats the right choice of words.
I have a list of records in a database, and based on each record, i may want a different function to process that record, the idea then is to have a field in the database which would be function_name, i then use that field to some how call that function.
Like this
test();
$function_name = "test";
function $function_name() {
echo "do something here";
}
the only way i can think to get around this is to use switch/case but that is going to cause me other issues down the line.
The function has to be defined with a specific name but you can call it using a variable that contains its name like so :-
<?php
function name() {
echo "name";
}
$func_name = 'name';
// its always a good idea to check that function
// actually exists before calling it.
if (function_exists($func_name)) {
$func_name();
}
Use closures for this:
<?php
$funcName = 'test';
$$funcName = function ()
{
echo 'Do something';
};
$test(); // 'Do something'
$$funcName(); // 'Do something'
Related
I understand how to implement a variable function though i don't understand it's use. Why call a function using a variable than to call the function itself?
Unless to dynamically call functions from user input or returned database results?
EXAMPLE : if you have an input like /?do=something
require_once('do.php');
$fun = 'do_'.$_GET['do'];
if (function_exists($fun)) {
$fun(); //variable function
} else {
not_found();
}
so in this case I just add a function to my do.php file and it will be ready to use
do.php :
<?php
function do_getkey() {
// do something when do=getkey
}
function do_sendkey() {
// do something when do=sendkey
}
function not_found() {
// when not found
}
?>
I just want to ask if its possible to call variables on class to another page of the site. I have tried calling the function's name and inside the parenthesis. I included the variable found inside that function e.g:
<?php
$loadconv -> loadmsg($msgReturn);
echo $loadconv;
?>
But it didn't work.
Do you want something like this?
class Load
{
public $msgReturn;
__construct()
{
}
public function loadMsg($param)
{
$this->msgReturn = $param;
}
}
Then you could do
$loadConv = new Load();
$loadConv->loadMsg('just a string');
echo $loadConv->msgReturn; // 'just a string'
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use a variable to define a PHP function
Use Variable as Function Name in PHP
I want to perform a conditional function call but I don't necessarily know what what the function will be, so that would be a long switch.
For example;
$userSelection = "calculator"; /* or "stocks" or whatever widget */
$widget->get_widget($userSelection);
public function __construct($userSelection){
/* pseudo code */
call function $userSelection();
}
public function calculator(){
/* Get Calculator */
}
Sure there is. This feature is called variable functions:
$functionName = "strlen";
$length = $$functionName("Hello world!");
The $$var(...) syntax is convenient, but it will only work with free functions. If you want to call a class method this way, you will need to use call_user_func or call_user_func_array (these functions can also handle the "free function" case).
Look at the call-user-func function. This allows you to call another function, e.g.
call_user_func('calculator')
call_user_func($userSelection);
http://php.net/manual/en/function.call-user-func.php
Take a look at this php functions:
call_user_func(): http://php.net/manual/de/function.call-user-func.php
call_user_func_array(): http://www.php.net/manual/de/function.call-user-func-array.php
create_function(): http://www.php.net/manual/de/function.create-function.php
There is also a direct (though ugly) execution syntax:
function some_func(args) {...}
$function_name='some_func';
$$function_name(args2);
You can use call_user_func() for that, like this:
$userSelection = "calculator";
call_user_func($userSelection[, $param1, $param2, ...]);
call_user_func_array($userSelection, $params);
If it's just a function you're after then using this should solve your problems
$function = "echo";
$$function "fooBar";
If it's a class method that you want to keep flexible use magic method __call() which will allow you to use method names that are not pre-defined.
__call() is triggered when invoking inaccessible methods in an object context.
i.e.
class Foo {
public function __call($name, $arguments) {
echo $name;
}
}
$foo = new Foo();
$foo->bar(); // will echo "bar"
PHP built-in function 'eval' can do everything, but beware of injection.
$var = "somefunction";
eval("$var();");
http://php.net/manual/en/function.eval.php
It's pretty simple if that's what you mean.
function calculator() {
echo 'foo';
}
$userSelection = "calculator";
if (function_exists($userSelection)) {
$userSelection();
}
Or within a class like in your example:
class widget {
public function __construct($userSelection) {
echo 'constructed widget<br>';
if (function_exists($userSelection)) {
$this->$userSelection();
}
}
public function calculator() {
echo 'bar';
}
}
$userSelection = "calculator";
$widget = new widget($userSelection);
Or from outside a class when the function is part of the class.
class widget {
public function calculator() {
echo 'bar';
}
}
$widget = new widget();
$userSelection = "calculator";
$widget->$userSelection();
I would work with if/else statements though to determine the function to be called just to be sure that only valid functions are executed (do you sanitize the user selection or do you just get it from a $_POST? The latter would be a very bad idea).
You can do following :
$var = 'abc';
switch ($var) {
case 'abc':
$result = $var('test param');
echo $result;
break;
default :
echo 'default';
break;
}
function abc($data) {
return $data;
}
I'm working on a project which requires a function to be copied & executed on the fly and variables in it needs to be replaced on the fly too.
A simple example will be like this:
function myfunction()
{
$abc = $_SESSION['abc'];
return $abc;
}
I want to be able to call myfunction1() which does NOT physically exist in the code but does exactly the samething as the one above except it now take values from my custom variable so it'll look like this:
function myfunction1()
{
$abc = $myCustomVariable;
return $abc;
}
Any one help pls?
The more you describe how convoluted your function is, the more it sounds like a perfect candidate for an object with injected dependencies.
For instance, you could have (just going to describe the basic interfaces here):
class myClass
{
public function __construct($provider DataProvider)
{
$this->provider = $provider;
}
// Please name this something better
public function doStufferer()
{
if ($this->provider->hasParam('foo'))
{
return $this->provider->getParam('foo');
}
}
}
class SessionProvider implements DataProvider
{
// Session specific stuff
}
class OtherProvider implements DataProvider
{
// Other provider stuff
}
interface DataProvider
{
public function getParam($key);
public function hasParam($key);
public function setParam($key, $value);
}
You can then use it like this:
$dataProcessor = new myClass(new SessionProvider);
// OR $dataProcessor = new myClass(new OtherProvider);
$dataProcessor->doStufferer();
Please take a look at PHP Classes and Objects and the other related topics.
This is what parameters are for, I think your looking todo something like this:
$myCustomVariable = 'Some value';
function myfunction($var=$_SESSION['abc'])
{
$abc = $var;
return $abc;
}
myfunction(); //returns $_SESSION['abc']
myfunction($myCustomVariable); //returns "Some Value"
The direct answer is eval which I do not recommend.
You could have your function accept a parameter, like this.
function myfunction1($some_var)
{
$abc = $some_var;
return $abc;
}
// call it like...
myfunction1($myCustomVariable);
If you need to access a variable, but the name is generated by dynamic code, you can use $GLOBALS.
function myfunction1($name_of_var)
{
$abc = $GLOBALS[$name_of_var];
return $abc;
}
// call it like...
$myCustomVariable = 'a value'
myfunction1('myCustom' + 'Variable');
I have a variable like $string = "blah";
How can I create a function that has the variable value as name?
Is this possible in PHP?
Like function $string($args){ ... } or something, and be able to call it like:
blah($args);
this might not be a good idea, but you can do something like this:
$string = "blah";
$args = "args"
$string = 'function ' . $string . "({$args}) { ... }";
eval($string);
That doesn't sound like a great design choice, it might be worth rethinking it, but...
If you're using PHP 5.3 you could use an anonymous function.
<?php
$functionName = "doStuff";
$$functionName = function($args) {
// Do stuff
};
$args = array();
$doStuff($args);
?>
Okay, challenge accepted!
No matter how weird the question is (it's not btw), let's take it seriously for a moment! It could be useful to have a class that can declare functions and make them real:
<?php
customFunctions::add("hello", // prepare function "hello"
function($what) {
print "Hello $what, as Ritchie said";
print "<br>";
}
);
customFunctions::add("goodbye", // prepare function "goodbye"
function($what,$when) {
print "Goodbye cruel $what, ";
print "I'm leaving you $when";
print "<br>";
}
);
eval(customFunctions::make()); // inevitable - but it's safe!
That's it! Now they're real functions. No $-prefixing, no runtime evaluations whenever they get called - eval() was only needed once, for declaration. After that, they work like any function.
Let's try them:
hello('World'); // "Hello World"
goodbye('world','today'); // "Goodbye cruel world, I'm leaving you today"
Magic behind
Here's the class that can do this. Really not a complex one:
class customFunctions {
private static $store = [];
private static $maker = "";
private static $declaration = '
function %s() {
return call_user_func_array(
%s::get(__FUNCTION__),
func_get_args()
);
}
';
private static function safeName($name) {
// extra safety against bad function names
$name = preg_replace('/[^a-zA-Z0-9_]/',"",$name);
$name = substr($name,0,64);
return $name;
}
public static function add($name,$func) {
// prepares a new function for make()
$name = self::safeName($name);
self::$store[$name] = $func;
self::$maker.=sprintf(self::$declaration,$name,__CLASS__);
}
public static function get($name) {
// returns a stored callable
return self::$store[$name];
}
public static function make() {
// returns a string with all declarations
return self::$maker;
}
}
It provides an inner storage for your functions, and then declare "real" functions that call them. This is something similar to fardjad's solution, but with real code (not strings) and therefore a lot more convenient & readable.
Try call_user_func_array()
php.net link
You can call a function by its name stored in a variable, and you can also assign a function to variables and call it using the variable. If it's not what you want, please explain more.