Jump to content
MakeWebGames

[FAQ] Quotes, and heredoc


Floydian
 Share

Recommended Posts

Quotes is something I think the beginner PHP programmer might not understand all the intricacies of the different types of php quotes and when to use them.

Three types of quotes are:

 

  • Single Quote -- '
  • Double Quote -- "
  • heredoc -- <<<EOT ...... EOT

 

Single Quote

The single quote is the fastest of the three types of quotes. The only caveat is this: if you need to concatenate your string a bunch of times in order to include variables, you're losing time because of starting and stopping the quotes.

Single quotes tells php to not look for variables.

 

<?php
echo 'This is NOT a $variable.';  // OUTPUTS: This is Not a $variable.
?>

 

This line of code will not print out the value of $variable. It simply sees this as pure text.

If you need to use the new line character (\n or \r\n), or the tab character (\t), these characters are printed to the screen as they are instead of being a new line or tab.

 

<?php
echo 'This will not give you a new line.\n'; // OUTPUTS: This will not give you a new line.\n
?>

 

Concatenating a string allows you to connect one string to another one, or some variable. A period is the operator that performs a concatenation.

 

<?php
$variable = 'SOME RANDOM VALUE';
echo 'We want to add in a variable such as ' . $variable . ', so that we can print it out.'; // OUTPUT: We want to add in a variable such as SOME RANDOM VALUE, so that we can print it out.
?>

 

Single quotes often conflicts with writing HTML because html normally requires quotes. Sometimes you can just use double quotes in your html, but if your text has any apostrophes, you'll be escaping them. javascript also brings in the need to use both single and double quotes which means you'll be escaping some of those as well, and that makes the code harder to read and debug.

 

<?php
echo '
<table class="head-table">
<tr>
<td>
This table isn\'t too bad as there is only one apostrophe, but the input button below is worse.
</td>
</tr>
</table>
<input type="button" onclick="some_function(\'arg1\', \'arg2\', \'arg3\')">
';
?>

 

**Random thoughts**

I normally use single quotes around small strings. If there is a need for one, maybe at the most, two things to be concatenated, that's fine. But any more than that, and I prefer a different approach that is outlined in the next two sections. Single quotes with lots of concatenation is very hard to read... And hence, is hard to debug.

I find that most of the times, a long section of text will have some variables in it so I normally go with heredoc by default.

 

Double Quote

Double quotes allow variables to be inserted into a string, and php will print out it's value. This benefit comes at a small price in the execution speed of the double quotes vs. the single quotes. PHP has to look at the entire string and determine if any of it contains a variable. Whereas with single quotes, that step is not needed.

New line characters work as new line characters when you are using double quotes. So make sure to use the double quotes instead of single quotes when you are working with new line characters.

Double quotes conflicts with html even more than the single quotes though. At least for me, I much prefer to use double quotes in html. It is prefered to do this, as javascript requires outer quotes to be double quotes and inner quotes to be single quotes. Note that it may work the other way around, but your professional Zend coder friends will laugh at you if you break that convention. ;)

 

<?php
echo "
<table class=\"head-table\">
<tr>
<td>
This example requires about the same amount of escaping as the last one. And I don't like escaping if I don't have to.
</td>
</tr>
</table>
<input type=\"button\" onclick=\"some_function('arg1', 'arg2', 'arg3')\">
";
?>

 

Take note of the javascript in the onclick attribute in this last example and how the onclick="" uses double quotes and the arg's inside that attribute use single quotes.

You can concatenate with double quotes just like you can with single quotes.

Whenever you have a variable that has [] at the end of it, this variable must have {} around it if you put it inside the double quotes.

 

<?php
echo "My name is $ir['username']"; // This example will not work. You will likely get an error on that.

echo "My name is {$ir['username']}"; // This is the way you need to do that.
?>

 

Class properties can be inserted into double quotes strings without using {}'s.

 

<?php
echo "The last MySQL error was: $db->mysql_error."; // This is 100% good code.
?>

 

You can put {}'s around any variable. This is helpful if your variable doesn't have a space after it.

 

<?php
$var1 = "www.";
$var2 = "phphorizons.com"; // yeah it's a silly example, sue me :p

echo "{$var1}{$var2}"; // OUTPUT: [url="http://www.phphorizons.com"]www.phphorizons.com[/url]

echo "$var1phphorizons.com"; // OUTPUT: (null)

echo "{$var1}phphorizons.com"; // OUTPUT: [url="http://www.phphorizons.com"]www.phphorizons.com[/url]
?>

 

**Random Thoughts**

I use this one more often than the single quotes. I like it because I can use apostrophes in smaller strings without any escaping. The speed issue is so minor it's not really a concern unless you're really scraping to save on CPU cycles. But by all means, don't let me stop you from optimizing your code as much as possible!

heredoc

And now we get to my favorite style of quotes of all. heredoc is the best of both worlds. It's faster than double quotes. (marginally)

My source for heredoc being faster is: PHP5 Advanced Quick Pro Guide, Page 451, Figure 12.5 by Larry Ullman. Single quotes is the fastest of all three though.

heredoc will print out the values of variables just like double quotes, and new line and tab characters are interpreted as new line and tab characters.

You can't concatenate heredoc. You have to end the echo, put in your extra code, and then start a new echo. I recommend getting all your text together before echoing anything out, and putting it all into one big heredoc block. But before I get to that, let's look at the syntax of heredoc because it's very particular.

echo <<<EOT

-------------

You will need put in three <'s and then three upper case letters. The three upper case letters serves as your quotes. After the <<<EOT, there can be nothing else on that line.

At the end of the string, you put:

EOT;

And that must go on a new line.

------------------------------------------------------

NOTE: It is noted by Decepti0n that the three letters can be of any length. This is true. I think you'll see that the conventional standard is three uppercase letters. Each person will almost always use the same three letters all the time, except out of necessity when those three letters appear inside the text being quoted.

------------------------------------------------------

 

<?php
echo <<<EOT
We must start on a new line like we did here.
We can insert $variables, and variables with []'s on them like: {$ir['username']} so long as it has the {}'s.
We can put in class properties: $db->mysql_error.
And when we close out the string, we must put our end quote on a new line, and it must have a semi colon, and nothing else on the line.
EOT;
?>

 

In order to avoid concatenating your strings, let's look at a sample query of an item table.

 

<?php

// Define and submit a query to the database.
$q_items = mysql_query('select id, name, sell_price, item_type from items');

// Initialize a variable that will contain the data from the query.
$item_list = null;

// perform a while loop to get the data from the query.
while(list($id, $name, $cost, $type) = mysql_fetch_array($q_items)) {

// Store the data in the $item_list variable, concatenate it each time to itself.
$item_list .= <<<EOT
<tr>
<td>
$name
</td>
<td>
$type
</td>
<td align="right">
$cost
</td>
<td>
[url="buy_item.php?id=$id"]Buy[/url]
</td>
</tr>
EOT;
} // End of while loop.

// Now that we have all the data stored and formated in the $item_list variable in the form of an html
// table that is only missing a start and end table tag, we can now do our echo all at once.
// Take particular note of how readable coding in this way is. :D

echo <<<EOT
<table>
<tr>
<th colspan="4">
<h2>Item List</h2>
</th>
</tr>
$item_list
</table>
EOT;
?>

 

One last thing of importance to note about heredoc, is that it can be used anywhere quotes are used. It's not limited to echo.

 

<?php
// call a function with arguments using heredoc.
some_function(<<<EOT
arg1
EOT
, <<<EOT
arg2
EOT
,);

// Take note how the comma does not go on the same line as the ending quote.

// We'll do the same thing with an array.


$my_array = array(
1=> <<<EOT
blah
EOT
, 2=> <<<EOT
foo
EOT
, 3=> <<<EOT
bar
EOT
,);
?>

 

I realize that this last example presents code that is harder to read than it's single and double quotes counterparts and hence, I use this sort of thing sparingly. But sometimes, it's just the thing to make life easier.

 

**Random Thoughts**

heredoc is by far my most used quote type. Well, I do use double quotes in more situations like using them in function call arguments and whatnot, but when it comes to displaying html to a user, heredoc is the preferred method.

New to PHP 5.3.0 is nowdoc.

The astute reader may have noticed that heredoc is more like double quotes than single quotes. However, there isn't anything like heredoc that acts like single quotes until you get to PHP 5.3.0.

I'll briefly introduce it here.

<<<'EOT'

blah

foo

bar

EOT;

This is nowdoc syntax. $variables are not seen when using nowdoc. nowdoc is useful instead of single quotes because single quotes don't need to be escaped ;)

Link to comment
Share on other sites

Re: [FAQ] Quotes, and heredoc

Thanks Spudinski ;)

 

Wth is ===> <?=$variable?>

Number one, short tags are not recommended. And number two, that's a syntax error, and number three, what is that even intended to do?

Anyways, wrapping or not wrapping text in start and end PHP quotes is a good way to have large amounts of text displayed.

 

I know you prolly won't take my word for it, but using a bunch of <?php and ?> in a script is horrible coding technique. Like I said, I know you won't take my word for it. But if you have a large block of text, like an HTML head that has no variables in it, leaving the text as raw text outside of the php tags is an excellent way to go.

However, I don't see that as being related to "quotes". Start and end tags are not quotes. Period. Hence they shouldn't be used on the fly to simulate quotes.

Link to comment
Share on other sites

Re: [FAQ] Quotes, and heredoc

Just a few things,

<?=$variable?> is valid and it's short for <?php echo $variable; ?>. You don't need the ; at the end because it's implied by the ?> bit, and the equals sign just means echo apparently.

Also, heredoc syntax can be any length of characters you want, it doesn't have to just be 3 characters

Overall, your best bet in the long run is to use a templating system

Link to comment
Share on other sites

Re: [FAQ] Quotes, and heredoc

That's what's up ;)

There's nothing wrong with using templates.

However, if "you", being a generic "you" encompassing any random person, is starting out completely new to coding, I'd recommend against using templates at first.

I think ones goal when initially learning a language should be to learn the language, and not how to use a template. If you're new to php, and you're new to some template for php, then you're learning two things at once.

After that, it's completely up to the person whether or not they want to use a template. There's advantages and disadvantages. Some pro coders use em, and some don't. It's really up to the person how they want to go.

Consider the case of using an ajax library. It is my opinion that some people turn to an ajax library because they don't know how to code an ajax request and they just want something to do it for them. That's fine.

I can tell you that I can do some crazy things with javascript and all without using any libraries, except in the case of JSON. Which is necessary to just about any substantial ajax application. But all of this goes way beyond the topic.

 

Which is ---- quotes.

If you wanna know about what the intricacies of quotes in php are, read the first post ;)

Link to comment
Share on other sites

Re: [FAQ] Quotes, and heredoc

I don't mean a php template sort of system like cakephp or codeigniter, I just mean a way to separate presentation and logic. In other words, calculate all your variables, and pass them through a function to display the actual html

People can do ajax without a library, but there's no reason to. I use jQuery when I need it, both for ajax and effects sometimes.

What library would you use for JSON? Just include this file and it's easy

Link to comment
Share on other sites

Re: [FAQ] Quotes, and heredoc

That is a library. It's short and small. But it's a library. lol

I use the YUI library and it's JSON implementation which is also written by Douglas Crockford. It's actually a better implemenation of the JSON methods than his standalone one.

No reason to do ajax without a library? I'm not sure what that has to do with quotes, but so be it. It's your opinion. Mine is, there is a reason to do just that. I also see reasons to use an ajax library. I think my concepts here are a bit more "open minded" than yours, no?

Be a bit more open minded. Not everyone will want to code like you do Deception ;)

So quotes? Any thoughts on quotes?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...