Forum Moderators: coopster

Message Too Old, No Replies

variable in function call

         

bkeep

2:06 am on Dec 4, 2010 (gmt 0)

10+ Year Member



Hey all, I am looking for some info on using a variable when calling a function.

Lets say I have two functions

function linkPaypal and function link2checkout

I have no issue calling the function like $x = linkPaypal(..); or $x = link2checkout(...); but what I want to know is can I make the function call dynamic so depending on the way a variable $vendor is set determines the actual function that is used ie

$vendor = 'Paypal'; then the call can be setup as
$x = link$vendor (item1,item2,etc);
which would call the linkPaypal function and return the appropriate info.

Thanks for any help.
Regards,
Brandon

bkeep

2:23 am on Dec 4, 2010 (gmt 0)

10+ Year Member



NM I figured it out pretty simple really RTFM doh!

[php.net...]
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.

for anyone that is interested the solution as it relates to the question
$pay_link_function = "link$vendor";
$pay_link_function (item1,item2,etc);

Regards,
Brandon

jatar_k

2:51 am on Dec 6, 2010 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



you can just use a switch or if statement as well

if ($vendor == 'paypal') {
or use strcmp or === or whatever you like

I have seldom found a use for variable functions, I actually found a use for it for the first time in 11 years last week

rocknbil

4:35 pm on Dec 6, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or just pass it as a parameter.

$my_result = my_function('my_value');

function my_function($val) {
if (! preg_match('/[^\w\-\_\d]+/',$val)) { return null; } // or some other condition
// Operate on $val
return $result;
}