Welcome to WebmasterWorld Guest from 3.227.208.153

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

variable in function call

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

Full Member

10+ Year Member

joined:June 1, 2007
posts:201
votes: 0


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
2:23 am on Dec 4, 2010 (gmt 0)

Full Member

10+ Year Member

joined:June 1, 2007
posts:201
votes: 0


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
2:51 am on Dec 6, 2010 (gmt 0)

Administrator

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 24, 2001
posts:15756
votes: 0


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
4:35 pm on Dec 6, 2010 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
posts:7999
votes: 0


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;
}