Curly brackets with no expression, conditional, or loop? [duplicate] - php

Is it possible to enclose code fragments in PHP within brackets (without using the fragment as a function)?
Would the following code behave the same way as it would without the curly brackets? Or might there be any problems depending on what kind of code used inside or outside the brackets?
For example, will this:
<?php
// First Code-Block
{# several lines of code
}
// Second Code-Block
{# another several lines of code
}
?>
Always behave the same way as this:
<?php
// First Code-Block
# several lines of code
// Second Code-Block
# another several lines of code
?>
Update:
One of the goals, as stated in "My1"'s comment as well, is to structure large code sections. Especially since most IDEs give you the option to collapse the lines between the brackets.
Especially in consideration of "dragondreamer"'s "Luke Mills"'s answers I played around with it a bit, and so far I didn't encounter any side effects. Of course, this might change with new PHP Versions in the future but "Luke Mills"'s answer gives good pointers on what to keep an eye on.

Yes, but it won't create a new local scope. It's not something that would normally be done. Usually people mark blocks like this with comments.
Update:
It took a bit of digging to find a reference to it in the manual, but here it is:
http://www.php.net/manual/en/control-structures.intro.php
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.
The key here is statements can be grouped into a statement-group by encapsulating a group of statements with curly braces.
I also had a look for a reference to variable scope as it relates to this situation, but the manual doesn't specifically mention it, however you can think of it like this:
In PHP, functions and classes create a variable scope. You can read about that here. But a statement-group (as described above) does not. Don't think of the curly braces of a statement-group like the function (or class) wrapping brackets, but think of them like the curly braces that wrap the statement-group of control structures (if, for, while, switch, etc.) - because that's exactly what they are. It's clear that if you're using an if statement (or any other control structure) that the braces don't introduce a new scope, they are simply wrappers for a block of statements.

PHP code behavior does not change if you enclose it within curly brackets. However, you can't use some PHP statements inside curly brackets:
namespace declarations;
namespace use declarations to alias or import any names;
global const declarations;
__halt_compiler().
This means, the following script will work:
<?php
const x = 5;
echo x;
but the following will not compile:
<?php
{
const x = 5;
echo x;
}

In one project I'm working on, I use statement-groups to indicate structure - in my case, parent/child relationships between nodes creates in a router:
$router = new Router();
$admin = $router->route('admin');
{
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
{
$menu->route('load')->get('load');
$menu->route('save')->get('save');
}
}
```
Internally, this builds a hierarchical structure like:
/admin
/upload
/menu
/load
/save
Calling route() in this example creates a child - so the code creates a model (inside the router) which has a tree structure, but the structure of the code does not reflect that.
I'm using curly braces here to make the code more legible, since reading the code without curly braces and indentation would be quite difficult:
$router = new Router();
$admin = $router->route('admin');
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
$menu->route('load')->get('load');
$menu->route('save')->get('save');
Indentation in this case really clarifies what's happening, I think.

I also do this, solely because of my text editor (Komodo Edit 8.5). It's not a "bad reason" or "bad coding", if it helps you and doesn't cause any problems and if there's no other easy way to do it.
I solve the problem with a work-around:
if(1 == 1){ //always executing if function
//whatever you want to add
}
#
adding a # at the end prevents my editor from collapsing all empty lines below the curly brackets. This helps to further structure the code.

Related

What is the purpose of a code block that isn't part of an if/function etc

E.g.
<?php
echo "hello word";
$test = 1;
{
//sample php code inside code block
}
?>
Why is sample php code inside that code block. Is it purely to keep any variables defined inside it within the scope of the code block so no variables outside the code block get over written?
It is most probably just for readability, since it doesn't create a new variable scope or something like this. Also as from the manual:
[...]Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.

May I omit curly braces in a function declaration?

Currently, I'm declaring functions in PHP like:
function theFunction($theVar) {
...
}
And in JavaScript like:
function theFunction(theVar) {
...
}
Can I omit the curly braces when the function only contains one line? Like:
function theFunction($theVar)
doSomething();
And:
function theFunction(theVar)
doSomething();
As far as I'm aware, that's not allowed by either language.
They both allow it for single-statement if()s and loops, but not for functions (and in the case of PHP, not for classes either).
But even if it was allowed, I'd strongly recommend against it; the braces are there for a reason, to aid readability and avoid ambiguity. I'd recommend always using them for if()s and loops for the same reason, even though they're not strictly required there.
Languages like Python get away without braces because they have very strict indentation rules. Without those rules, a language need braces (or some other block marker); if you don't use them, you run a very high risk of your code having logic errors.
No. The curly braces are required. (Try it and see for yourself).
No, neither PHP nor JS support this kind of declaration. The same is with try and catch blocks, which for some reason always require curly braces, even though condition and loop statements do not.
No, function declarations require a block regardless of how main statements are contained within.
function f()
console.log(x); // error: unexpected identifier

Use curly brackets to structure code in PHP

Is it possible to enclose code fragments in PHP within brackets (without using the fragment as a function)?
Would the following code behave the same way as it would without the curly brackets? Or might there be any problems depending on what kind of code used inside or outside the brackets?
For example, will this:
<?php
// First Code-Block
{# several lines of code
}
// Second Code-Block
{# another several lines of code
}
?>
Always behave the same way as this:
<?php
// First Code-Block
# several lines of code
// Second Code-Block
# another several lines of code
?>
Update:
One of the goals, as stated in "My1"'s comment as well, is to structure large code sections. Especially since most IDEs give you the option to collapse the lines between the brackets.
Especially in consideration of "dragondreamer"'s "Luke Mills"'s answers I played around with it a bit, and so far I didn't encounter any side effects. Of course, this might change with new PHP Versions in the future but "Luke Mills"'s answer gives good pointers on what to keep an eye on.
Yes, but it won't create a new local scope. It's not something that would normally be done. Usually people mark blocks like this with comments.
Update:
It took a bit of digging to find a reference to it in the manual, but here it is:
http://www.php.net/manual/en/control-structures.intro.php
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.
The key here is statements can be grouped into a statement-group by encapsulating a group of statements with curly braces.
I also had a look for a reference to variable scope as it relates to this situation, but the manual doesn't specifically mention it, however you can think of it like this:
In PHP, functions and classes create a variable scope. You can read about that here. But a statement-group (as described above) does not. Don't think of the curly braces of a statement-group like the function (or class) wrapping brackets, but think of them like the curly braces that wrap the statement-group of control structures (if, for, while, switch, etc.) - because that's exactly what they are. It's clear that if you're using an if statement (or any other control structure) that the braces don't introduce a new scope, they are simply wrappers for a block of statements.
PHP code behavior does not change if you enclose it within curly brackets. However, you can't use some PHP statements inside curly brackets:
namespace declarations;
namespace use declarations to alias or import any names;
global const declarations;
__halt_compiler().
This means, the following script will work:
<?php
const x = 5;
echo x;
but the following will not compile:
<?php
{
const x = 5;
echo x;
}
In one project I'm working on, I use statement-groups to indicate structure - in my case, parent/child relationships between nodes creates in a router:
$router = new Router();
$admin = $router->route('admin');
{
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
{
$menu->route('load')->get('load');
$menu->route('save')->get('save');
}
}
```
Internally, this builds a hierarchical structure like:
/admin
/upload
/menu
/load
/save
Calling route() in this example creates a child - so the code creates a model (inside the router) which has a tree structure, but the structure of the code does not reflect that.
I'm using curly braces here to make the code more legible, since reading the code without curly braces and indentation would be quite difficult:
$router = new Router();
$admin = $router->route('admin');
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
$menu->route('load')->get('load');
$menu->route('save')->get('save');
Indentation in this case really clarifies what's happening, I think.
I also do this, solely because of my text editor (Komodo Edit 8.5). It's not a "bad reason" or "bad coding", if it helps you and doesn't cause any problems and if there's no other easy way to do it.
I solve the problem with a work-around:
if(1 == 1){ //always executing if function
//whatever you want to add
}
#
adding a # at the end prevents my editor from collapsing all empty lines below the curly brackets. This helps to further structure the code.

Concise syntax for javascript if statements without curly brackets

So pragmatically, I've got a quick and dirty answer to what I'm looking for here. But why isn't using that a good idea? Why can't I find any formal documentation of it? Is it not part of the spec and standard? Is it not widely supported? Is it just because minification could break code using that syntax?
If you could point me to more comprehensive docs of the feature, I'd appreciate that. What defines the contents of the if block? Is it indentation based? If it was, that'd be interesting.
On another note, is there something similar to this syntax for if statements in PHP? I can swear that I've seen them being used here and there, but I can't find any examples off hand. Am I just crazy and it actually doesn't exist in PHP, or can those types of if blocks be used in PHP? Does such an if block support having an else as well, both in JS and PHP?
It seems that there's an indentation based one as well as a single-line based syntax as well. What can you tell me about the following?
if(condition) do_some_statement();
Thanks
But why isn't using that a good idea?
Because it's hard to maintain.
Why can't I find any formal documentation of it? Is it not part of the spec and standard?
Of course it is, see §12.5 - The if Statement and §12 - Statements in the spec. The body of an if is a Statement. One kind of Statement is Block (§12.1), which allows a list of statements to be treated as one statement, but there are many other kinds of statements.
Is it not widely supported?
Universally.
Is it just because minification could break code using that syntax?
A good minifier won't break that syntax. (A good minifier will make use of it, in fact.)
What defines the contents of the if block? Is it indentation based?
The body of an if statement consists only of the statement following it, indentation has no significance in JavaScript. So all of these are equivalent:
if (foo)
bar();
charlie();
if (foo) bar();
charlie();
if (foo)
bar(); charlie();
if (foo)
bar();
charlie();
In the above, only the call to bar is conditional on foo; charlie is called regardless.
That's why we have Block, the Statement that introduces a list of statements to be treated as a unit (a block, you might say :-) ):
if (foo) {
bar();
}
charlie();
if (foo) { bar(); }
charlie();
if (foo) {
bar(); } charlie();
if (foo)
{ bar(); }
charlie();
Indentation is important for humans, though, so keeping consistent indentation is a good idea. The first example in each of the above is probably clearest (of the ones listed) for us mere mortals. :-)
On another note, is there something similar to this syntax for if statements in PHP?
I'm not a big PHP-head, but it looks identical, defined in Control Structures - if. There are examples with and without {}. (There's also a different, alternative syntax I won't go into here.)
Does such an if block support having an else as well, both in JS and PHP?
Yes, if supports else both with and without blocks.
javascript is not white space sensitive, meaning
if(condition) do_some_statement();
is the same as
if(condition)
do_some_statement();
that being said, omitting braces in a single line if statement is always frowned upon because it can lead to bugs if the if statement ever needs to be modified:
if(condition)
do_some_statement();
// someone adds another line here, without adding the braces
// now you've introduced a bug
also, is it really that hard to write { }? :P
The statement following an if is just that: a statement.
One of the possible forms a statement can take is that of a brace-enclosed group of statements.
Thus, the syntax of an if statement is
if ( expression ) statement
Thus the reason that braces improve maintainability is that they provide an explicit boundary to the scope of influence of the if control flow effect.
why isn't using that a good idea?
It is far to easy to add another statement and expect it to only fire if the if passes
Why can't I find any formal documentation of it?
The MDN documentation:
Statement that is executed if condition evaluates to true. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ({ ... }) to group those statements.
ECMA-262 (page 89):
if ( Expression ) Statement
It seems that there's an indentation based one
No. Just an if, then a condition, then a statement. The statement can be formatted on the same line or the next line.
White space is not significant in JS.
It is standard, part of the spec (if-statement, other statements) and supported everywhere. Minification does not break it, because whitespaces have no semantics in JS - it even will enforce it for one-line-statements to save the two braces.
So, it is widely used (without problems!) as well. Sometimes it is considered bad because appending statements to the indented body without adding the braces can lead to problems. Also, it can lead to erratic behaviour when used in nested ifs:
if (false)
if (whatever)
;
else
alert("");
Would you have expected an alert? No, the else belongs to the last if.
Yet, you can use it unconcerned for one-line-statements that are sure not to get extended, like return;.

PHP curly brace syntax for member variable

First question on SO and it's a real RTM candidate. But I promise you I've looked and can't seem to find it. I'll happily do a #headpalm when it turns out to be a simple thing that I missed.
Trying to figure out Zend Framework and came across the following syntax:
$this->_session->{'user_id'}
I have never seen the curly braces syntax used to access what appears to be a member variable. How is it different than
$this->_session->user_id
I'm assuming that the _session is irrelevant, but including it in the question since it may not be.
Are the curly braces just a cleanliness convention that attempts to wrap the compound variable name user_id? Or is it some kind of a special accessor?
Any pointers into TFM so I can R up would be humbly appreciated.
Many thanks. Please be gentle.
Curly braces are used to explicitly specify the end of a variable name. For example:
echo "This square is {$square->width}00 centimeters broad.";
So, your case is really a combination of two special cases. You're allowed to access class variables using curly braces and like so:
$class->{'variable_name'} // Same as $class->variable_name
$class->{'variable' . '_name'} // Dynamic values are also allowed
And in your case, you're just surrounding them with the curly brace syntax.
See the PHP manual, "complex (curly) syntax."
I know the syntax just when using variable variables:
$userProp = 'id';
$this->_session->{'user_'.$userProp};
Theres probably one big advantage of that syntax, however, its generally in the domain of hairy stuff, and things you probably want to avoid.
It permits you to use characters in variable names that are otherwise unpermitted.
ie:
$this->object->{"hello world\0\n"}
$this->object->{"function(){ this is a truely awful name for a variable }"}
In the example you give, there's no real difference, and IMO $this->_session->user_id should be used because it's clearer.
What the curly brace syntax is actually good for is accessing a member variable by constructing an expression for its name, like $this->_session->{'user_id' . $index}.
The two examples in your question do the same thing. PHP allows you to access member data/methods in several ways...
object->{'name_of_member'};
object->name_of_member;
$member = 'name_of_member';
object->$member;

Categories