简体   繁体   中英

PHP Switch Case Counter

I'm very new to PHP and I'm developing in the context of WordPress (with ACF). I'm creating a custom layout builder, I got it working but I want to make my code simpler. Right now is 14 cases which load a __.php file if is applicable. Here is an example snippet:

switch (get_row_layout()) {

    case 'row_1' :
        include ('template_row_1.php');
    break;

    case 'row_2' :
        include ('template_row_2.php');
    break;

    case 'row_3' :
        include ('template_row_3.php');
    break;

}  

Keep in mind I have 14 total cases (for now). They are named row_1 --> row_14 and the templates files are also named sequentially.

Is there any way of coding this without using so many switch cases? What if I include another row in ACF and I want to avoid coding another switch case.

I was thinking a counter which counts the total layouts inside the builder and switch case loops through them. Does this makes sense? I just want to make my code simpler and avoid the repetitiveness of the statements.

Thanks!

You could dynamically create the name of the file to be loaded.

Something like this:

$row = get_row_layout();
include ('template_'.$row.'.php');

这很容易

include ('template_' . get_row_layout() . '.php');

Can you please try this ?

 if ( get_row_layout() ){
       $str = get_row_layout();
       $file_name = 'template_' . $str . '.php';
        include( $file_name  );
    }

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