Search code examples
phpvariablesmethodscall

Using a define (or a class constant) to call a variable method?


Is it possible to :

define('DEFAULT_METHOD', 'defaultMethod');

class Foo
{
    public function defaultMethod() { }
}

$foo = new Foo();
$foo->DEFAULT_METHOD();

Or do I have to :

$method = DEFAULT_METHOD;
$foo->$method();

And what about a class constant instead of a define ?


Solution

  • If you use a variable or constant as the method name, you have to put it into curly brackets:

    $foo->{DEFAULT_METHOD}();
    

    The same technique works for variables, including static class attributes:

    class Foo {
        public static $DEFAULT_METHOD = 'defaultMethod';
        public function defaultMethod() { echo "Cool!\n"; }
    }
    
    $foo = new Foo();
    $foo->{FOO::$DEFAULT_METHOD}();
    

    In fact, practically any expression that results in a valid method name could be used:

    $foo->{'default'.'Method'}();