0

I have the following example code

<?php

class Test {
    function foo() {
        print "foo\n";
    }

    function bar() {
        $func = 'foo';
        $func();
    }
}

$test = new Test();
$test->bar()

which calls $test-bar(), whiich internally calls a variable php function named foo. This variable contains the string foo and I want the function foo be called like here. Instead of getting the expected output

foo

I get an error:

PHP Fatal error:  Call to undefined function foo()  ...

How to do this right, when using a string for the function-name? The string 'func' might denote several different functions inside the class scope in the actual code.

According to the doc the above should work like I have coded, more or less...

1
  • 0_0 How about using data structures rather than horrors like $func = 'foo'; $func();? Commented Aug 14, 2013 at 17:42

3 Answers 3

5
<?php

class Test {
    public function foo() {
        print "foo\n";
    }

    public function bar() {
        $func = 'foo';
        $this->$func();
    }
}

$test = new Test();
$test->bar();

?>

Use this for accessing the current function of this class

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that is what I was looking for. Maybe someone could add this to the php docs...?
0

What you can do is use the function call_user_func() to invoke the callback.

<?php

class Test {
    public function foo() {
        print "foo\n";
    }

    public function bar() {
        $func = 'foo';
        call_user_func(array($this, $func));
    }
}

$test = new Test();
$test->bar();

Comments

0

You use the keyword $this

<?php

class Test {
    function foo() {
        print "foo\n";
    }

    function bar() {
        $this->foo(); //  you can do this

    }
}

$test = new Test();
$test->bar()

There are two ways to call a method from a string input:

$methodName = "foo";
$this->$methodName();

Or you can use call_user_func_array()

call_user_func_array("foo",$args); // args is an array of your arguments

or

call_user_func_array(array($this,"foo"),$args); // will call the method in this scope

1 Comment

I do not want to call the function directly, I need a string with the function's name. I have updated the question to make this point clear. Sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.