PHP Literal output with ?> in function definition - php

When writing PHP code in the past, I have often been plagued by the awkwardness of having to nest my HTML code in calls to print, echo or similar. This is alleviated to some degree by the ability to make parts of the code be literally outputted by closing the PHP tag and reopening it again after the output, eg:
<?php /*DoSomeStuff*/ ?>
Some HTML code.
<?php /*SomeMorePHP*/ ?>
However, I have never been clear on how this interracts with functions. For example, it is unclear to me if writing:
<?php
function myFunction() {
?>
Some HTML
<?php
}
?>
Will produce a function which upon being called will output that HTML, if the function will be parsed as empty but output that HTML during parsing, or neither, both or if this construct is just illegal entirely?
I am reluctant to base all my results on just trying this on some particular instance of PHP as I do not wish to beleive it works while in reality it might be undefined behaviour or think it doesnt work while I might just have an old or buggy PHP and I have never seen this construct used in any code.
Ideally I am looking for some kind of reference to documentation or specification which would clear this up.

I know this is not exactly answering your questions with a lot of references, but: This is valid (PHP Docs), although it doesn't look very nice, it's a common practice in some old but BIG frameworks.
You can try this and see what happens:
function htmlOut() {
?>
Some HTML output
<?php
}
htmlOut();
By the way I found an example, the default skin of MediaWiki (I would say they know what they are doing) is using just the method you have described.
/**
* Outputs the entire contents of the (X)HTML page
*/
public function execute() {
/**
* some code
*/
// Output HTML Page
$this->html( 'headelement' );
?>
<div id="mw-page-base" class="noprint"></div>
<div id="mw-head-base" class="noprint"></div>
<div id="content" class="mw-body" role="main">
<a id="top"></a>
<?php
/**
* some more code
*/
}
See the full code here: MediaWiki GitHub

Basically it will work as you expect it to be, which means that this HTML will be printed only on function invoke.
There's probably no documentation for your use case, but it's similar to condition expressions.
You could ask if similar question for code below:
<?php if ($expression == true): ?>
HTML1
<?php else: ?>
HTML2
<?php endif; ?>
Will PHP print both HTML parts, or only one depending on the condition?
Well, the doc says clearly that it works as it is expected to be.
I think we can say it's the same for functions/methods, because it's just "a block of code". It works with the same rule in many other cases like loops or swich
Reference: http://php.net/manual/en/language.basic-syntax.phpmode.php Example #1

Related

PHP delimiters and WordPress (functions.php in specific)

I am modifying the functions.php file of a child theme in a wordpress installation.
At some point I want a function to produce html and then proceed as a normal function.
The "normal" way for me to code this would be like that:
<?php
/**
* Child Theme
* Author: Seb
**/
function html_output() {
# some php code here
?> // closing php delimiter
// some html code here
<?php } # opening php delimiter to close the function
# more php code here
However, when looking at code from other people online, the last two lines are like this:
<?php } ?> // opening php delimiter to close the function and then closing delimiter
<?php # random (?) extra php delimiter I don't get the meaning of
The editor (Coda and Sublime Text 2) doesn't complain about my code but it doesn't work. Can someone maybe explain to me why this has to be like that in order to function properly?
EDIT:
To make my question more clear, I don't understand how
<?php }
is different to
<?php } ?>
<?php
Though I am not sure about your question, but I got two thing in my mind
Coding Style for each developer differs ( while keeping the code
healthy , and as per the standard being used on that specific
framework)
it is a practice, I have often noted that you always have an OPENED
<?PHP tag in code, the reason what I think I read somewhere was that ,
it helps us avoid HEADERS ALREADY SENT ON LINE..... ERROR
Also, this opened <?php tags denoted that you have a php file and if
you want to add any peice of code after this, you have to follow
PHP standards / rules in mind
Okay
for php point of view
<?php } ?>
<?php
and
<?php }
both are okay, and they are as per php rules, but when it comes to WP, where, you get your final html rendered by including 3 or more than files, sometime, it becomes problematic....think the following situation
header.php
<?php }
and now, contents.php
<?php
//and some php code goes here
say, to load the page, both files are combined, so final output would be something like
<?php }
<?php
//and some php code goes here
just trying to explain you the situation with an example, not specific thoug...

Conditional embed HTML between PHP code blocks?

I'm fairly new to PHP. I started learning it like 3 weeks ago. I cannot find the answer to this question on StackOverflow, Google or Youtube. The PHP documentation to this just confuses me. To get on with the question, how does PHP code mixed in with HTML work?
<?php if (something) { ?>
<p>Hello</p>
<?php } ?>
The p element will only display if something has a truthy value, how is this?... I thought for sure that the PHP engine ignored what was going on around the outside of the codeblocks (e.g. <?php ?>) and only parsed what happens on the inside.
The code below gets parsed by the PHP engine normally and sent to the browser without affecting any HTML elements (even though its clearly between 2 code blocks).
<?php echo $something; ?>
<p>Hello</p>
<?php echo $something; ?>
I hope I'm not going to get flamed for asking this question since a lot of people seem to understand how it works in like a tenth of second.
P.S. I asked this question in chat early and thought I understood it correctly but when I went to implement it my mind was still like, how does this work exactly? It just seems like some kind of hack to me.
Easy now. Definitely need a php tutorial for you to start on http://www.tizag.com/phpT/
Here is what your doing:
<?php
//Anything inside me php processes
if($something)
{
echo "<p>something</p>";
}
//About to stop processing in php
?>
<p>Anything outside of the php statement above will just be printed to the dom</p>
Quick Note: It is good practice to separate your PHP from your HTML
<?php if ($something) { ?> <-- where is the other {
<p>Hello</p>
<?php } ?> <-- oh I see it.
In your first example it is indeed true that <p>Hello</p> will be rendered if and only if 'something' returns true.
If you close a php tag with ?> but have an 'unclosed' execution, like if (blah) { ..., the PHP engine understands your desires and does accordingly.
Why?
The PHP engine is kept 'waiting' until the execution is closed with } and then the final result is evaluated and the browser continues on with the lines below.
Obviously if you leave out the final } you will see some errors, which tells you that PHP was expecting you to finish what you started and you did not
Both the php and html are parsed in-line. So, as it moves down your script it will run php scripts within tags, and display html in the order which they are placed. For example:
<? $someVar = "someVar string value"; ?>
<h1>This is a title</h1>
<? if(1 == 1){?>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<? } ?>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: <?=$someVar;?></p> // <?= is a short hand for echo
This will show as:
<h1>This is a title</h1>
<p>This paragraph will appear in between the header tags because 1 == 1 is true</p>
<h3>Another header which will follow the paragraph</h3>
<p>The value of someVar is: someVar string value</p>
Basically just think of it as the server reading down your script and parsing whatever it sees as it goes. If there is html, it will display it and if there is php which does some sort of calculation and then spits out html, it will show the spat out html.
You can write php code anywhere in HTML using php code block
<?php echo "whatever " ?>
or
<?php echo "<h1>Here everything will displayed in h1 </h1> "; ?>
and if you use control structure ( if, switch etc.. ) then it will behave like all other languages, means if something is true then it will execute the part written between { }.
so if you write an undefined variable in if condition then it will not execute code block of because undefined variable is treated as false condition .
additionaly you can check any variable value by var_dump($variable)
PHP's Alternative syntax for control structures
<!DOCTYPE html>
...
<div>
<?php if ( the_thing === true ) : ?>
<p>The thing is true! \o/</p>
<?php else if ( the_other_thing === true ) : ?>
<p>The other thing is true! meh</p>
<?php else : ?>
<p>Nothing is true :-(</p>
<?php endif; ?>
</div>
...

If I don't use a template engine with my PHP, what should my code look like?

I don't want to use an MVC framework. I don't want to use a template engine. I am a few man shop where the developers where all the hats, no graphic artists. We do it all (all layers). I do not want code mixed with presentation, like I have with Classic ASP.
But, I do not know what my code is suppose to look like between server side and the actual presentation.
If I'm not emitting HTML in my server side code, how does it get to the HTML page so I can do things like <span><?= $myvar ?></span>? and put loops in the html page?
Thank you for any advice.
For using loops and all, I use the alternative syntax for the control structures.
An example:
<div id="messages"<?php if(!(isset($messages) && count($messages))): ?> class="hidden"<?php endif; ?>>
<?php if(isset($messages)): ?>
<?php foreach($messages as $message): ?>
<div class="message"><?php echo $message; ?></div>
<?php endforeach; ?>
<?php endif; ?>
</div>
For more information, see this: http://php.net/manual/en/control-structures.alternative-syntax.php
Oh also, I use a semi-MVC structure, where I have a class that handles templates (views), basically it's just a class that I create an instance of, pass a set of variables, then render the template when the instance get destroyed. I have an array of variables in that class, and then use extract to pass all variables in the include, like so:
extract($this->variables, EXTR_SKIP);
include($this->file);
EDIT: Here is the same example in Smarty:
<div id="messages"{if isset($messages) && !count($messages)} class="hidden"{/if}>
{if isset($messages)}
{foreach from=$messages item=message}
<div class="message">{$message}</div>
{/foreach}
{/if}
</div>
Simple PHP projects usually generate the full HTML in-place instead of populating templates, so you'd just echo it out in your PHP code.
This gets messy, so you WILL end up coding some kind of templating system for any moderately complex website.
A possible alternative is to serve your page as completely static HTML/CSS and use AJAX to fetch the actual contents dynamically (JSON would be a good transport format, it's native to JS and can easily be generated from PHP). This gets you rid of all the HTML littered across your PHP code. Whether this is a viable alternative or not depends on the case.
<span><?= $myvar ?></span> works.
A loop would look like:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>
Example taken from here.
I really recommend that you use the php Template Inheritance system. (Don't let it scare you, it's only one file.) This is a simple set of functions that helps you to build extensible PHP views without the problems and limitations of manual includes.
It's still Pure PHP, so you don't need to learn some strange template language. It may not look like much, but it's really powerful once you start using it.
To be sure, you can do it all by yourself - but what you want is still MVC pattern, or separation of concerns ("I do not want code mixed with presentation"). Or at least MV, for very simple applications (although it's still dirty, having models directly influence the view).
The easiest way to achieve this is to first collect and process all data, then just print them. No complex code allowed in the php files directly exposed to the web.
<?php
require('model.inc');
process_capuchin_monkey_order_form();
?>
...
<h1>Thank you for your order of <?php echo $order->num_monkeys; ?> monkeys.</h1>
...
typically you would want to just make sure you have as little PHP in your HTML as possible. This means doing all of the data processing before hand, and simply passing a set of variables in one way or another to a method or function that includes the HTML.
Any HTML with PHP intermixed could be considered a template. Here's a simplified example:
// view class
class View {
public function render($html_template) {
include('view_path/' . $html_template . '.php');
}
}
// html template file 'view_path/main.php'
<html>
<body>
<h1><?= $this->title ?></h1>
</body>
</html>
// usage
$view = new View();
$view->title = 'Some Title';
$view->render('main');
You should use an MVC-like separation of concerns no matter what you do. This means:
At least one file is all html and is given a handful of variables. (view/template)
At least one file is all php and only talks to the database. (model)
At least one file processes the http request, pulls data from database, and executes the view.
The core of every php templating language is the use of extract() and include inside a function:
function render_template($___filename, $___data) {
extract($___data, EXTR_SKIP);
include $__filename;
}
You can pretty this up with a class interface (view objects) or with output buffering, but this is the core of every template system. Your controller's responsibility is simply to assemble that $__data argument (usually with data from a database) for a given view.

How to write class/function that returns large amount of html

I'm used to using includes with large chunks of html outside of the php code, but I'm trying to move to classes or functions because they have increased flexibility and potential for design patterns etc.
I need a function right now that will return a large amount of html, mixed in with some php variables, but I'm looking for away to keep the code outside of the <?php declaration so that it will be formatted like proper html and have code hinting, rather than being a gigantic string.
If it's possible, how would I go about formatting/writing that?
I would do something like this...
function getPage() {
ob_start();
include("file_with_html.php");
$content = ob_get_clean();
return $content;
}
Of course, you can add other functionality as needed. But, the advantage here is that you're using output buffering. Without this, the data is sent to the user right away. But, using the ob_start() and ob_get_clean(), you can return it and work with it some more.
You can use include('somefile.html');.
include works with vanilla HTML too.
If you need to have it "mixed in with some php variables", just add those when you need them. Remember: PHP, by its very nature, is a templating language.
For example:
outerHTML.php:
<?php function generateCode($username) { ?>
<h1>Welcome back, <?php echo $username; ?></h1>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<?php } ?>
main.php:
<?php
// some PHP code
include('outerHTML.php');
generateCode('John');
// some more PHP code
?>
Also, you can use output buffering within your classes. See comments at http://php.net/manual/en/function.ob-start.php

Strange PHP tags

I got the code below from a tutorial that teaches how to make wordpress plugins. It has some unusual PHP tags. For example,
a) 3rd line from the bottom, there is an opening <?php tag.
b) And, also, after $base_map_url is set, there is a closing ?> tag.
This is very different from what I've learned, yet the code works.
c) Also, in all the plugins the author has built, there is an opening <?php tag at the very top but not a final closing one.
What is happening here, can you explain?
<?php
/*
Plugin Name: Map plugin using shortcode
Plugin URI: http://example
Description: This plugin will get a map of whatever parameter is passed
Author: Drew
Version: 1.0
Author URI: http://www.blah
*/
function smp_map_it($addr)
{
$addr = "1600 Pennsylvania Ave. Washington, D.C.";
$base_map_url = 'http://maps.google.com/maps/api/staticmap?sensor=false&size=256x256&format=png&center=';
?>
<h2>Your map:</h2>
<img width="256" height="256"
src="<?php echo $base_map_url . urlencode($addr); ?>" />
<?php
}
add_shortcode('map-it','smp_map_it');
It is just leaving a PHP block for HTML output.
Functions shouldn't really do that. That is why WordPress gets so much crap, e.g. the_content() that just dumps content (as if people are too incompetent to use echo).
The best way to do it is simply have a view file which handles your HTML and some basic PHP constructs and control structures such as echo, foreach, if, etc.
The trailing ?> in a file is unnecessary, and Zend coding standards ask you to never place it. It can often be the cause of Headers already sent when some pesky whitespace ends up after it.
When you close the PHP tag, it just becmes equal to:
echo ('<h2>Your map:</h2>
<img width="256" height="256"
src="');
There are two approaces to coding PHP. One inserts PHP into HTML, this is used by frontend developers. Template languages use this style in general:
<img src="<?php echo ($url); ?>">
The other style is more like programming then template writing:
<?php
echo (printf ('<img src="%s">', $url));
<?php marks the beginning of php code for the php parser
?> marks the end of php code for the php parser
/* marks the start of a comment which will be ignored by the parser
*/ marks the end of a comment which will be ignored by the parser
This function is sending output directly rather than using echo statements where the content falls outside the php tags.
While this kind of approach is often discouraged (coming out of the PHP context while in a function body isn't considered good practice) there isn't anything about it that would make it not function.
It is however, very bad code. Outputting in function bodies very often leads to header errors and other comforts when trying to perform redirects or session management.
It is not strange, it is crap. He is embeding HTML in PHP (sin anyway), and he is doing it bad.
Last PHP tag can remain open.

Categories