Question

Don't know if I worded the question right, but basically what I want to know is if there is an easier (shorter) way of doing the following:

switch( $type ) {
    case 'select': $echo = $this->__jw_select( $args ); break;
    case 'checkbox': $echo = $this->__jw_checkbox( $args ); break;
    case 'radio': $echo = $this->__jw_radio( $args ); break;
    case 'input': $echo = $this->__jw_input( $args ); break;
    case 'textarea': $echo = $this->__jw_textarea( $args ); break;
    default: return null;
}

Is there any way I could do something like $echo = $this->__jw_{$type}( $args );? I tried this code but of course, it failed. Any ideas?

Was it helpful?

Solution

$field = "__jw_$type";
$echo = $this->{$field}($args);

or even more simply,

$echo = $this->{"__jw_$type"}($args);

OTHER TIPS

Try this:

$method = "__jq_$type";
$echo = $this->$method($args);

Alternatively, use call_user_func:

$method = "__jq_$type";
$echo = call_user_func(array($this, $method), $args);

Of course, there's no validation on the method name here.

There are many ways you could do it, here's one:

if(method_exists($this, "__jw_$type"))
{
    $echo = $this->{"__jw_$type"}($args);
}
$action = "__jw__$type";
$this->$action($args);

Of course, you'll really want to verify that $type is an allowed type.

You can try something like this:

$type = '__jw_'.$type;
if(method_exists($type,$this))
   $this->{$type}($args);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top