简体   繁体   中英

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 ?

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'}();

You could set it to a variable first as in your example :)

Example: http://codepad.org/69W4dYP1

<?php
  define('DEFAULT_METHOD', 'defaultMethod');

  class Foo {
      public function defaultMethod() { echo 'yay!'; }
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM