Defining a method name using a variable

I was just wondering if there’s actually any way to define the name of a class’s methods using variable names (whose value would be retrieved from the database)?

i.e.



class Test {

   public function $methodname {


   }

}

AFAIK, there is no way to use variables in defining the classes and methods in general.

Even if it were, why would you do that?! Perhaps you can explain more about what you want to achieve. You can generate a class based on something in the database, but having a variable function definition would be like approving plans for your house that had $flooring instead of carpet/tile/solid_gold/etc.

It’s basically because the method names are tied to different sections of a db driven table that holds details on the site’s template. So, if the template has a section labeled ‘header’, then there needs to be a corresponding header method in classes that are relevant.

Making sure I add the necessary method names is not a problem, but I was just imagining a situation in which I happen to change the name of a section. Currently, this would result in me having to go through all the classes that were calling the old method name and find/replacing the old name with the new one.

Any ideas on what the best work around for my issue would be without making any change to the design/logic to the structure?

Just have a method head($template) where $template is what you change - either the name or the template code. You wouldn’t change head() to foot() would you? Method names should reflect what the code does.

Not quite sure I fully understand you here - can you please elaborate a little more?

Without seeing your code it’s a stab in the dark, but essentially:
If you want to change a section, then you swap one section for another, the method remains the same
function render($section) { include $section.php; }

If you want to refactor your code so render() becomes renderSection() then refactor your code.

Excellent. That could possibly be very useful indeed.

Much thanks, hash.

Funky stuff…


class TestCase
{
  /**
   * @param string $method
   * @param array $args
   */
  public function __call ( $method, array $args ) {
    var_dump( $method, $args ); }
}

$t = new TestCase;
$t->SomeRandomMethod( 'arg1', 'arg2', 1, 2 );

/* Output:
  string(16) "SomeRandomMethod"
  array(4) {
    [0]=>
    string(4) "arg1"
    [1]=>
    string(4) "arg2"
    [2]=>
    int(1)
    [3]=>
    int(2)
  }
*/

The __call magic method logic_earth is getting at was the first thing that came to mind for me too.