Tuesday, January 24, 2012

PHP String Heredoc

Assume:
You know how to program in php

Any Web Server programmer will encounter PHP and one of the biggest headaches in PHP (IMHO) is understanding strings. 


First, this is an excellent article on php strings.

http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm


Today though I want to concentrate on a tool that can help out.  As you know when you insert HTML or Javascript code in PHP things can get ugly in a hurry mainly due to the problems with quotes.   Sadly a basic keyboard only has two characters for quotes :  ( double "  and a single ')  But look at this example:

echo ( "onclick='DoAJavaScript ( 'Fred', 'Bob')' ");

This code won't work for several reasons but as you notice when we came to the variables of (Fred and Bob) we needed yet another set of quotes to cover that issue.  The problem is we used the double quotes to start the string and then the single quotes to start the Javascript call 'DoAJavaScript' leaving nothing left for the parameters. 

WHAT DO I DO????
Well there are a couple of solutions.  You can take advantage of the ESC '\' character sequence.  The key idea is that you use \" instead of a " to wrap a string and now the code gets really ugly:

echo ("onclick='DoAJavaScript ( \"Fred\", \"Bob\" ");

Wow this is getting really ugly and there is another problem.  PHP will only evaluate code with a double quote.  Everything else it takes literally...a real mess!!!

Example:

$Fred = "Hello";
echo ("$Fred");
// You get:   Hello

echo ('$Fred');
// You get: $Fred

However...don't fret.  There is a most convenient but hardly talked about function in PHP that is a lifesaver.  It is called heredoc and despite the convoluted name it works magnificently.

$Fred = <<<BLOCK

onclick='DoAJavaScript ('Bob', 'Fred');

BLOCK

Sweet.  With this crazy block of code you don't need starting and ending quotes saving you a serious headache.  Now take a look at the format.

BLOCK -> Notice that BLOCK starts and ends the string.  They have to be the same name and have to be upper case...AND have to be on the left hand side of the document.  (In other words, don't indent otherwise it won't work.

<<<  (This sends the information to the string.)

$Fred (The string variable.)

Now take advantage of this the next time you create a messy string structure.

No comments:

Post a Comment