Reza Saadati
Reza Saadati

Reputation: 1274

Dynamic method names

I would like to call a method dynamically. Since I have many methods, which start with set, the rest of the method name should be dynamic.

This is what I have tried so far:

$column = 'City';

function setCity() {
    echo 'London';
}

set${column}();

I get the error message:

syntax error, unexpected '$'

Upvotes: 0

Views: 55

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57121

You can build the function name before calling the function...

$func = "set{$column}";
$func();

Upvotes: 1

Gavin
Gavin

Reputation: 2365

call_user_func will achieve this.

$column = 'City';

function setCity() {
    echo 'London';
}

call_user_func("set$column"); // London

Upvotes: 0

Related Questions