StackOverflowNewbie
StackOverflowNewbie

Reputation: 40653

PHP variable declaration has parenthesis

The following code appears to both be valid:

$a = ('hello');
$b = 'world';

I'm not familiar with this parenthesis notation, though. What is it for? How is it different without the parenthesis?

Upvotes: 0

Views: 176

Answers (4)

Cranio
Cranio

Reputation: 9847

In this case there is no difference.

Parentheses mean that this is an expression, and it's result will be stored in the variable.

In this case the expression does "no operation" at all:

$a = ('hello');

so parentheses are completely useless. In other cases, you just consider them like an expression, much as a mathematical one.

Upvotes: 1

jonny
jonny

Reputation: 4673

The parentheses allow you to force a certain order of evaluation for the involved operators, e.g. when you use non-commutative operators, such as -:

$x = (2-2)-2; // = -2
$x = 2-(2-2); // =  2

Since you don't perform any operation, you can simply discard or add parentheses at will.

Upvotes: 1

Luc
Luc

Reputation: 985

Similar to all basic maths. It helps separate calculations. E g. (2x2)+3=7 but 2x(2+3)=10.

It instructs the compiler to deal with each instruction in a certain order.

Upvotes: 4

Fad
Fad

Reputation: 9858

There's no difference between the two. Using parentheses only tells PHP to evaluate the expression before doing anything else.

Upvotes: 3

Related Questions