What causes this difference of syntax? - php

Look at the code below
<?php
echo "$_SERVER[HTTP_HOST] <br />";
echo $_SERVER['HTTP_HOST'], "\n\n";
?>
both of the echo statements return the value of HTTP_HOST index from the superglobal array $_SERVER using the same technique? My question is what caused the difference of the syntax? I noticed the following differences:
HTTP_HOST in the first echo statement is not encased in single quotes, it is contrary to the syntax I used in the second echo statement. I get the following error if I encase HTTP_HOST in single quotes for the first echo statement
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\php-blog\simple-blog\server.php on line 2
Why a comma is needed after ['HTTP_HOST'] in the second echo statement while it is not needed in the first echo statement? I get the following error if I discard this comma.
Parse error: syntax error, unexpected '"\n\n"' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';' in C:\xampp\htdocs\php-blog\simple-blog\server.php on line 3
I am new to programming, need guidance, help please.
Thank you!

Your first statement calls echo with only one argument.
The argument is a string which includes a variable.
When doing this you should use brackets to make sure php understands were your variable starts:
echo "{$_SERVER['HTTP_HOST']} <br>";
You could also concatenate strings with a dot:
echo $_SERVER['HTTP_HOST'] . "<br>";
The comma is just another way to write several echos at once:
echo 1, 2;
is the same as
echo 1;
echo 2;
http://php.net/manual/en/function.echo.php

php syntax allows referring to variables inside double-quotes.
for example:
$x = "hello";
echo "$x world";
is similar to:
echo $x . " world";
or
echo $x , " world";
and all will output hello world.
notice that referring to variables inside single-quotes is not allowed, and for this reason
echo '$x world';
is invalid.

Related

Printing variables in PHP the difference between these two methods?

I’m learning to program in PHP and I learned that I can print variables with text through different methods but I have a question:
What is the difference between echo $var1 . ' ' . $var2 and echo "{$var1} {$var2}" in PHP? And what to use?
I don’t understand why do we have use curly brackets and even if it is another method what is the difference between the two.
Thank You!
The first method is the concatenation method and is straightforward.
The second method:
you can print variables inside double quotation marks like
echo " $var1 $var2 ";
but what if you want to print something directly b/w, before, or after a variable. e.g:
echo " $var1SomeOtherTextNotFromVariable$var2SomeMoreText ";
PHP will assume that all text as variable until another $ is reached.
To solve this you need to tell PHP where does variable start and end. e.g:
echo " {$var1}SomeOtherTextNotFromVariable{$var2}SomeMoreText ";
Note
Please check Progrock's answer for another benefit of using curly braces.
Per your comment:
No, I know the difference between double quotes and single quotes I just don’t understand why do I need to put curly brackets
You don't "need" curly brackets but they can help in reading your interpolated string.
Please do not do this in your code but consider:
<?php
$hi = 'h';
$hii = 'sh';
echo "$hiie";
Do you get hie or she as the result?
Answer: neither, you get
Notice: Undefined variable: hiie
To fix this then you need to be explicit with one of the following lines:
echo "{$hi}ie"; // hie
echo "{$hii}e"; // she
(Not an answer but worthy of consideration.)
Curlies are useful if you are dealing with arrays:
$foo =
[
'name' => 'Foo',
'age' => 23
];
echo "Name: {$foo['name']}, Age: {$foo['age']}\n";
Output:
Name: Foo, Age: 23
If you omit the curlies you get an error like:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in ...

What exactly does $object->{0} do?

I've seen in this answer the code
$tmpNode = parent::addChild($name,null,$namespace);
$tmpNode->{0} = $value;
I'm curious what the ->{0} actually does? Which PHP language construct is this? Does it reference the first property of $tmpNode without using its name?
Update:
I've seen the answers given so far, but I was looking for a reference into the PHP language manual that explains this use of curly braces. When I search in the PHP Manual for curly the only hit is to the page about strings where curly's are only explained in the context of variables and complex expressions. It wasn't clear to me that the language allows curly's around literals.
Curly brackets {} in php are also used to parse complex codes. Take this for example:
$t = 0;
$$t = 5;
echo ${0}; //outputs 5
or this:
${0} = 65;
echo ${0}; //outputs 65
but if you were to try this:
$0 = 65;
echo $0;
you would get:
Parse error: syntax error, unexpected '0' (T_LNUMBER), expecting variable (T_VARIABLE) or '$'
It is the same with object properties:
$obj = new stdClass();
$obj->{1} = "Hello world";
echo $obj->{1}; //outputs "Hello world"
Complex (curly) syntax

Unexpected T_Variable parse error in PHP

I have this PHP code and getting this error:
Parse error: syntax error, unexpected '$e' (T_VARIABLE)
In this line:
$error = echo 'Captured: ', $e->getMessage(), "\n";
I got this information from here. I just wanted to save the echo to a variable. What am I doing wrong here?
Comma is not a concatenation operator in PHP, Period is. Secondly, echo doesn't return the string back, it only outputs it. Remove the echo and save your string in your variable like this:
$error = 'Captured: '. $e->getMessage(). "\n";
Now you may wonder that if this is the case then why do you have an example on PHP.net having comma there?
echo 'Captured: ', $e->getMessage(), "\n";
It is because that is not string concatenation, those are 3 different parameters being sent to the echo command so in that case it is valid syntax, but for string concatenation it wont be.

Unexpected "'String"' error (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';'

Today i was working with some codes when I met this error to make it simplify I have made an simple code which returns this error:
$i=1;
echo $i*5."<br/>";
Error
syntax error, unexpected '"<br/>"' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';'
Here I am trying to multiply an integer variable with an integer value and then add some string afterwords.
the solution I found to escape this error is to simply replace $i*5 by 5*$i but it my question is why does this happens.In my scope ov view there is no syntax error but if there is any please let me know.
The reason for the error is the . after 5 which makes compiler confused whether 5 is an integer or an floating value i.e it expects some digits after . but it gets "<br/>"
You can add an space after the digit so that the compiler gets to know that number is over like this :
$i=1;
echo $i*5 ."<br/>";
The correct syntax is either
echo $i*5, "<br/>";
// You can echo more than one expression, separating them with comma.
or
echo $i*5 . "<br/>";
// Notice the space.
// 5. is interpreted as ( float ) 5

PHP - Error parsing a string with code

I'm having a problem with some code that used to work in PHP 4.X and is not working in PHP 5.2.4
First of all, there is a small example of a code similar to the one is causing the problem. Unfortunately, I haven't been able to reproduce the problem with a small example.
<?php
class Example{
public function showExample()
{
$ind = 1;
$m = "method";
$str2 = "{call method}";
$str2 = str_replace("{call $m}" , "<?php print( \$pre$ind ); ?>", $str2);
echo $str2 . "\n";
}
}
$e = new Example();
$e -> showExample();
?>
What this code is doing is building a string with some php code to execute later on. In particular, the code generated will print the value of a variable named "$pre" + a variable number. In this case, the output is the following:
<?php print( $pre1 ); ?>
Everything runs fine with this code. The problem is when I use it in the context of a much bigger class, that is part of a framework I've been using for a long time. I cannot paste here the whole source of the class, but the problematic lines are the following (I simplified them a little bit to remove the str_replace, but the error still appears):
$myVar = "value";
$myVar2 = 2;
$str2 = "<?php print( \$myVar$myVar2 ); ?>";
When I load the file, I get the following two messages:
PHP Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /Users/giove/Sites/mundial/htmltemplate.php on line 252
PHP Parse error: syntax error, unexpected T_VARIABLE in /Users/giove/Sites/mundial/htmltemplate.php on line 252
I can fix the warning by removing the '\', but that changes the semantics of the code, so it's not a real possibility.
Now, the weirdest part is I can remove both errors by breaking or removing the sequence "
This seems to be a difference in versions, but I haven't been able to find any mention to it on the change logs.
Now I've got a working solution from Cryo: split the string
"<?php"
to prevent its 'evalution' (I'm not sure if that's really an evaluation).
Nevertheless, I still would like to know the reason for this weird behavior.
Cryo: thanks for your help, I'll mark the question as answered in a couple of days.
My guess is that PHP is catching on the re-opening of the php tag <?php, try splitting just that:
$str2 = "<?" . "php print( \$myVar$myVar2 ); ?>";
Or use single quotes and concatenation:
$str2 = '<?php print( $myVar' . $myVar2 . ' ); ?>';
Cryo is on the right track, though I think the actual issue is that PHP evaluates variables within double-quoted strings. However, the slash should prevent the variable from being evaluated. So:
$a = "somestring"
$b = "\$a" // -> \$a
$c = '\$a' // -> \$a
I think your string is getting evaluated in an odd way such that the \ + $myVar is evaluated in a strange way.

Categories