PHP - Call object methods dynamically via variables


I am trying to unit-test some of my code and it would be easier to just call my setters dynamically based on some variables. Unfortunately my approach does not work as expected and I couldn't find more information regarding on how to do that.

I have one variable which always is a string. It is used as property name and together with the "set" keyword it should result in "setSomething" or "setSomethingElse".

I already tried

// or

But those do not seem to work.

Maybe someone of you pro's know the right approach ;)!




You need to make the entire method name a variable, or enclose the whole name in{} e.g.

class test {
    public $Something;
    public $SomethingElse;

    function setSomething($value) {
        $this->Something = $value;

    function setSomethingElse($value) {
        $this->SomethingElse = $value;


$property = "Something";

$t = new test;
$setter = "set$property";
echo $t->Something;

$property = "SomethingElse";
echo $t->SomethingElse;



Demo on

People are also looking for solutions to the problem: php - Error "unique table/alias" when joining 2 tables


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.