Position of <?php script | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Position of <?php script

Will placement of "<?php.... " rather in head or body affect productivity of page? If yes, can it be used for optimisation and in what kind of situation?

10th Jan 2017, 3:18 PM
Denis
4 Answers
+ 3
PHP scans the entire page for its tags. Until it finds one, it's just dumping the HTML it finds into an output buffer. When it finds a PHP tag (<?php or <?= usually), it 'switches contexts' and fires up its PHP interpreter engine (hopefully not every time) to add 'special' process stuff to the output buffer. At its end tag it switches contexts streaming to output again. Strictly considering tag placement, efficiency would be more about switching contexts THE FEWEST TIMES possible than where those tags appear (because HTML is just text with special tags to PHP...the client/browser understands + bootstraps the DOM). Some people do stuff like this: <?php if (condition): ?> <div>HTML for true condition</div> <?php else: ?> <div>HTML for false condition</div> <?php endif ?> It works...but I think it's ugly, forces coders to slow down and you're switching the engine three times for something you could just do in one block. Maybe it doesn't matter...but I still don't like it.
10th Jan 2017, 3:53 PM
Kirk Schafer
Kirk Schafer - avatar
+ 3
I should add...you can force PHP to flush (send output stream data) early - especially for long-running pages. In this scenario you probably want your context switch as early as possible.
10th Jan 2017, 3:59 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Really don't matters on performance but just for maintain order and good php practice. Basic Just before create dynamic data. open tag. Functions, class separated pure php file called by include on head page. Advanced. Separate Views of pure PHP files and include on head
10th Jan 2017, 3:31 PM
nextco
nextco - avatar
0
Agree, the main problem here is: PHP by definition is for incrust anything on html. Summary: To fix just put a cache manager on the middle In a common practice all data is called on top file position like <?php // get values ?> Now how access to var and set for, while bucles? like this for a link <a href=<?=$myData?> > Cool Name </a> To fix this behavior put a static or dynamic cache on the middle and be happy. php is a cool language sometimes misunderstood.
10th Jan 2017, 4:12 PM
nextco
nextco - avatar