1
class Foo
{
    public $abc;

    function __construct() {
        $this->abc = function(){
            echo "new function";
        };
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$foo->Bar();  // echo "This is Bar"

How can I call the $abc variable function from the outside?

3
  • 2
    $foo->abc() doesn't work? Commented Jun 3, 2014 at 16:03
  • ^--« Seems like that comment is being contradicted. Commented Jun 3, 2014 at 16:05
  • 1
    @NiettheDarkAbsol: Sadly, nope. eval.in/158339 Commented Jun 3, 2014 at 16:06

2 Answers 2

6

abc isn't a method of Foo, so you can't just do $foo->abc();. abc is a property. You first need to get the property, then call it.

$abc = $foo->abc;
$abc();

DEMO: https://eval.in/158342

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

4 Comments

@Fred-ii-: I had this same issue a while ago, so I wanted to throw in my knowledge ;)
Nice and clear. Prefer this to the 'call_user_func' solution (+1 for both).
(Previous) experience pays off then ;-)
@kingkero: I think doing $this->abc = function() is more ugly ;) If you want to add a method to a class, then do that. I don't think you need a anonymous function. That's what's causing the ugliness :)
4

Alternatively, you can use call_user_func:

call_user_func($foo->abc);

As of PHP 7 you can do the following:

($foo->abc)();

Comments

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.