PHP - Call object methods dynamically via variables

927

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

$obj->set{$property}($value);
// or
$obj->set$property($value);

But those do not seem to work.

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

883

Answer

Solution:

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";
$t->$setter(4);
echo $t->Something;

$property = "SomethingElse";
$t->{"set$property"}(8);
echo $t->SomethingElse;

Output

4
8

Demo on 3v4l.org

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

Source

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.