1

I usually create modular websites, each part of the website being a .php file which will be included in the main pages.

Is it "better" to output HTML within PHP files using echo or to close each time the php tag ?> and open it each time I need to access a PHP function/variable.

V1:

<?php    
$v1=$_POST['name'];    
echo "Your name is".$v1;
echo $v1." if you want, you can log out";
?>

V2:

<?php $v1=$_POST['name']; ?>    
Your name is <?php echo $v1; ?>
<?php echo $v1;?> if you want, you can log out

The thing is that between the php tags there's much more HTML code (echoed) than actual PHP.
Does it affect the script performance if I close the tags each time? And is it safe to acces variables declared in a previous block of php code?

EDIT1: When closing the php tags isn't the server clearing some cache for that script, or something like that?

1
  • It is safe to use variables declared in another php block. I would say just pick the method you like and stick to it. Commented Sep 3, 2011 at 22:27

3 Answers 3

2

I think you can select whatever you want, but you should use it everywhere. For myself, second one is better

Sign up to request clarification or add additional context in comments.

Comments

2

Definitely v2. Plus , you additionally should read this one : http://codeangel.org/articles/simple-php-template-engine.html (archive link: http://archive.is/CiHhD).

1 Comment

@feeela , no it isn't. Especially not when you have a large piece of HTML.
0

Using V2 would be better as it wouldn't break the syntax highlighting or code completion in many IDEs, but both of them are as good as the other. As far as I know, there is no (considerable) difference in performance.

You could also consider using a template engine, however, that does impact performance. The most popular template engine is Smarty, but there are others (some better, some worse) out there.

3 Comments

Actually the article Teresko points to shows how php itself is already a template engine, and advises against blind use of template engines...
I think simply creating a file header.php then including it it's easy & fast enough for me :D . I've done some sites this way and with some other "speed optimizations" they load almost instant even though the hosting isn't that good. :)... +1 for answering
I did read, after posting my comment. But forgot to edit. Edited now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.