PHP - To echo or not to echo?

前端 未结 7 1034
[愿得一人]
[愿得一人] 2021-01-31 06:05

What is more efficient and/or what is better practice, to echo the HTML or have many open and close php tags?

Obviously for big areas of HTML it is sensible

7条回答
  •  孤街浪徒
    2021-01-31 06:27

    From a maintenance perspective, one should have the HTML / XML as separate from the code as possible IMO, so that minor changes can be made easily even by a non-technical person.

    The more a homogeneous block the markup is, the cleaner the work.

    One way to achieve this is to prepare as much as possible in variables, and using the heredoc syntax:

    // Preparation
    
    $var1 = get_value("yxyz");
    $var2 = get_url ("abc");
    $var3 = ($count = 0 ? "Count is zero" : "Count is not zero");
    $var4 = htmlentities(get_value("def"));
    
    // Output  
    
    echo <<
       
    • $var2
    EOT;

    You will want to use more sensible variable names, of course.

    Edit: The link pointed out by @stesch in the comments provides some good arguments towards using a serializer when producing XML, and by extension, even HTML, instead of printing it out as shown above. I don't think a serializer is necessary in every situation, especially from a maintenance standpoint where templates are so much more easy to edit, but the link is well worth a read. HOWTO Avoid Being Called a Bozo When Producing XML

    Another big advantage of the separation between logic and content is that if transition to a templating engine, or the introduction of caching becomes necessary one day, it's almost painless to implement because logic and code are already separated.

提交回复
热议问题