SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
-
Oct 9, 2009, 15:47 #1
- Join Date
- Nov 2001
- Location
- Fort Lauderdale
- Posts
- 814
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Question about the use of Curly Braces
I've been working with PHP for awhile, but usually just modifying existing PHP code. I'm currently taking a class on lynda.com to brush up and to make sure i have good coding habits.
Here is an example they give, it's just an example of an echo statement.. and they said to use curly braces when you want to attach a word or statement to a variable with no space.
Here is the example:
PHP Code:<?php
$my_variable = "Hello World";
echo "{$my_variable}Again!.";
?>
Once the PHP code starts getting complex, would this cause issues or is this good practice?
Thank you in advance.
-
Oct 9, 2009, 16:03 #2
- Join Date
- Oct 2009
- Posts
- 14
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thats the way I do it, if I am not modifying the variable at all then I'll just curly bracket it into the statement. But if I was going to escape the strings then I'll set a new variable and then place it in the echo:
//Not Modifying A Variable/Session
echo "Hello, {$_SESSION['username']}";
//Modifying A Variable/Session
$username = stripslashes($_SESSION['username']};
echo "Hello, $username";
I developed CMSs, forums, blogs and never had a problem using the curly brackets.
-
Oct 9, 2009, 21:48 #3
- Join Date
- Jul 2008
- Posts
- 5,757
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Most people seem to prefer avoiding anything tricky when it comes to putting variables inside of double quotes. The common way is to not do it, and instead use string concatenation.
PHP Code:echo $my_variable . "Again!.";
-
Oct 9, 2009, 22:47 #4
Heya.
I use the brackets for when I am passing an object through a MySQL query, which is usually only like:
-- because I need the single quotes inside the get() so it doesn't think userID is a constant.
PHP Code:$db->query("
UPDATE users SET
`hp` = `hp` - '$lose_hp',
`total_battles` = `total_battles` + '1'
WHERE `id` = '{$sess->get('userID')}' LIMIT 1
");
If Im not using many lines in notepad Ill just concenate the string.
PHP Code:<?php
echo "
<h2>{$usr['login']} of {$usr['empire']}</h2>
<br />Level: {$usr['level']}
<br class='clear' />
<div class='graph'>
<strong class='bar' style='width: {$usr['hp']}%;'>HP {$usr['hp']}</strong>
</div>
";
// etc..
Bookmarks