Why backslash is present before variable in eval statement? - php

While learning PHP online I am stopped at this eval function please help me. Why is there is a slash before $str2 in eval statement?
<?php
$string = "beautiful";
$time = "winter";
$str = 'This is a $string $time morning!';
echo $str. "<br>";
eval("\$str2 = \"$str\";");
echo $str2;
?>

The slash escapes the dollar sign, else in double quotes the dollar signs starts a variable name.
echo $var; // print the content of $var
echo "$var"; // print the content of $var
echo "\$var"; // print '$var'
echo '$var'; // print '$var'
Other thing is that you should find another book/tutorial for studying. Usign eval is unrecommended and in this case bad.
The last two lines of your code should be:
$str2 = $str;
echo $str2;
OR just
echo $str;

eval parses a string as php code, if you would remove them, both $str and $str2 would be replaced by their contents before it would get parsed by eval.
So with backslashes it would parse
$str2 = "This is a beautiful winter morning!";
Without the backslash it would parse
undefined = "This is a beautiful winter morning!";

Because it help identify that variable is used and variable with backslash are recognized by Compiler and then variable name is replaced with the value that it represents.

Backslash used to recognize PHP specials characters. In this case, \$str2 indicating a string contain "$str" not a variable named $str which is value 'This is a $string $time morning!'. So \$ while printed as string $ not as a variable.

Related

Understanding the eval() function of php

I'm a designer trying to upgrade myself into a coder-designer. Lately I've been looking into some PHP codes and manuals, then I ran into an example code for the eval() function :
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
This is an example code of eval() function in official PHP website, and although it did help me understand the eval() function, I can't figure out how the example code works. to be more specific, I can't understand why
("\$str = \"$str\";")
results in a merged string.
I really can't figure out why this should work.
Ok, here is what we have:
eval("\$str = \"$str\";")
Look, the string is in double quotes: it means that the $ character will be interpreted as a variable start. So we screen this character with a backslash: \$, then it will "mean" just a normal dollar sign. Also, the double quotes inside the string had to be screened too.
In the end we are getting this string: (I changed the quotes to single so $ dont confuse you): '$str = "$str";'. Look, it looks more like a normal code now :)
Evaling it, PHP will do the following (I removed the outer quotes for convenience):
eval( $str = "$str" );
Notice the double quotes here, too. It means that the variable inside, again, will be parsed/interpreted.
As $str was originally == 'This is a $string with my $name in it.', it will be inserted into the expression, and now it will look like:
$str = "This is a $string with my $name in it.";
And, again, double quotes! It parses and substitutes variables $name and $string, giving us at the end:
$str = "This is a cup with my coffee in it."
Voila!
A mindbreaker, but a really good example to learn the mechanisms.
you should get two console.log like this
This is a $string with my $name in it.';
This is a $cup with my $coffe in it.';
Why? well first you print the value, of $str , without eval, and later, you eval them, basically this happens,
First.
Print $str, without eval.
This is a $string with my $name in it.';
Second
this piece of code, runs eval("\$str = \"$str\";");
Eval replace $string and $name. with the 2 new variables values, which are $cup and $coffe
Hope you get it

I got trouble with eval() function in php?

i have searched this function on google a lot. However, i can't understand this function clearly.
i have a example:
<?php
//eval dangerous to use
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1><?php echo $motto;?><br/>";
echo $str.'<br />'; //result: welcome
eval("?>"." $str"."<?php echo $motto;"); //error
echo $str;
?>
eval() takes a string and evaluates it as PHP code. Here are some important points to note:
eval() takes PHP Code as it's argument -- not mixed HTML markup. Currently, you're passing a string containing HTML markup.
You don't need to add <?php ... ?> tags in the string. eval() already knows the argument is going to be PHP code (it's supposed to be), so you don't need to tell it
Here's a very short example:
$motto = "lksdfasdkf";
$str = 'echo $motto;';
eval($str); // => lksdfasdkf
Here, the string $str contains the literal string echo $motto;, which is a valid statement in PHP. When you call eval($str); the string gets evaluated as PHP code. In this case, it will echo the contents of the variable.
Note that this wouldn't work if you use double-quotes instead:
$motto = "lksdfasdkf";
$str = "echo $motto;";
eval($str);
If you have error reporting enabled, then you'll get the following error:
Notice: Use of undefined constant lksdfasdkf - assumed 'lksdfasdkf' in
The reason is that variables are not parsed when they're wrapped in single-quotes. When you use double-quotes to define your variable, the variable value gets interpolated into the resulting string, meaning $str will contain the literal string echo lksdfasdkf; -- which is not valid PHP code. The solution is to escape the dollar character to avoid it being interpreted as a variable:
$motto = "lksdfasdkf";
$str = "echo \$motto;";
eval($str); // => lksdfasdkf
eval — Evaluate a string as PHP code - your code also working fine
try
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1>$motto<br/>";
echo $str.'<br />'; //result: welcome
eval("\$str = \"$motto\";");
echo $str;

single quotes and double quotes in php?

Double quotes--->"$a" interpretes variables.
single quotes--->'$a' does not.Alright till now
MyQuestion:
what if I use "'$a'"?
Note:want to know behind the scene details.
Detailed Explanation:
I faced a major problem because of this when I used it in a foreach loop:
The following example gave me incorrect option value. For example, value it renders is UX if original is UX developer
echo "<option value=".$item['m_designation'].">".$item['m_designation']."</option>";
this example gave me correct option value. For example,value it renders is UX developer if original is UX developer
echo '<option value="'.$item['m_designation'].'"> '.$item['m_designation'].' </option>';
Hope I am clear.
Update:
I got the desired result but I don't know the logic behind it. I have tried it and done it successfully, but I wanted to know what's happening behind the scene. I think people have misread my question.
The use of ' and " for strings only changes when they are the outer container of the entire string - a different quote inside that is just treated as a plain character with no special meaning, therefore "'$var'" uses the rules of " (parsing variables), whereas '"$var"' would literally output "$var" as it uses the rules of ' (no parsing of variables).
Summary:
When you do "''" or "\"\"" the quotes inside the string are not parsed by PHP and treated as literal characters, the contents of such quotes will have the same behaviour in or out of those quotes.
You'll have a string that uses double quotes as delimiters and has single quotes as data. The delimiters are the ones that matter for determining how a string will be handled.
$a = 'test';
echo '$a';// prints $a
echo "$a";// prints test
echo "'$a'"//prints 'test'
double quotes checks the php variable and echo the string with php variable value
example echo "wow $a 123"; //prints wow test 123
single quotes print whatever in the single quotes
example echo 'foo $a 123';//prints foo $a 123
Your 'faulty' (first) string was missing the single quotes ':
echo "<option value='".$item['m_designation']."'>".$item['m_designation']."</option>";
^ ^
Your problem is that you confuse the quotes in your HTML with the quotes in the PHP.
$a = 1;
$b = '"$a"';
echo $b;
# => "$a"
$a = 1;
$b = "\"$a\"";
echo $b;
# => "1"
I'd advise you to simply never use string literals, as (especially in PHP) there are a lot of unexpected and weird edge-cases to them. Best is to force an interpreter (which also only works with double quotes:
$a = 1;
$b = "\"{$a}\"";
$c = "{$a+2}";
echo $b;
# => "1"
echo $c;
# => 3
It seems your question is more directed toward the output PHP produces for HTML formatting. Simply, single quotes in PHP represent the literal value:
$a = 1;
$b = '$a';
echo $b;
//$a
$a = 1;
$b = "$a";
echo $b;
//1
$a = 1;
$b = "'$a'";
echo $b;
//'1'
If you want to output HTML, you can use heredoc syntax. This is useful when outputting more than one line containing variables:
$name = "Bob";
$age = 59;
echo <<<EOT
My name is "$name".
I am $age years old.
EOT;
//My name is "Bob"
//I am 59 years old.

dollar escape? pay me $$owed

I ran into a block of code that executes print with double quotes around the argument. The argument contained a variable that was seemingly escaped by a dollar sign. Is that how a variable is called inside double quotes in php?
print("$$owed");
Here's the full block from the source:
<html>
<head>
<title>Loans</title>
</head>
<body>
<?php
$interest_rate = .14;
function YouOweMe($cost, $interest_rate) {
$weekly_payment = ($cost*$interest_rate);
print "You better pay me $$weekly_payment every week, or else!";
}
<font color="#000000">YouOweMe($cost, $interest_rate);
?>
</body>
</html>
I had to strip the numbers. So annoying.
Anyway, ... What doesn't make sense to me is that $$owed is supposed to, what? Create a new variable from a separate variable that contains a string 'owed'? That doesn't seem practical in any situation. Isn't $$owed just to get a dollar sign before the amount?
Here is an example to understand variable variables :
<?php
$var = "test";
$test = "hey !";
echo "$$var"; //$test
echo "${$var}"; //hey !
echo '$$var'; //$$var
?>
Edited according to comments.
In PHP, a variable is escaped with $ when inside a string defined with double quotes. This does NOT work with single quotes.
$string = "world";
echo "Hello ${string}";
#### outputs "Hello World"
That is how you put a variable into a string (you need the double quotes).
What you have is variable-variable. You can call a variable $foo by using a string with foo in it.
$string = 'foo';
$foo = 'hello world';
echo "I say, ${$string}";
Would output "hello world.
There are a couple of ways to use variables inside double quotes, some common ways are
print("$owed") will print the value of $owed
print("$$owed") is called a "variable variable" (as linked previously)
$owed = "test";
$test = 16;
print("$$owed");
will print out "$test".
Another use of this comes in the form of print("${$owed}"), which takes the value of $test and uses it as the variable name.
I strongly advise you to use single quotes and concatenate the variables needed, as it saves the time for evaluating variables in out, e.g.:
$owed = 42;
print('The value is: ' . $owed);
lg,
flo

What is the different between {$hello}, ${hello} & $hello when use double quotes?

I'm a bit confuse with
$hello = "hello";
echo "Say $hello";
echo "Say {$hello}";
echo "Say ${hello}";
and the output is same Say hello. When should I use {$hello} and ${hello}? and why it cannot be used in single quote?
$animal = 'cat';
echo "I have 14 $animals";
This may lead to problems, thus you will "escape" it
echo "I have 14 ${animal}s";
or
echo "I have 14 {$animal}s";
In single caused variables/expression were never substituted.
Single quoted string will never expand variables in PHP. See:
http://php.net/manual/en/language.types.string.php
for more detail of the string formats in PHP. There are 4 in total (including nowdoc introduced in PHP 5.3). Only double quoted and heredoc string formats cause variables to be expanded.
According to http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing ,
this is a simple syntax:
echo "Say ${hello}";
and this is a curly syntax:
echo "Say {$hello}";
Why does them both output the same? Becaus in PHP you can use variable variables in every place you want. For example:
$var = 'somevar';
$bar = 'var';
echo $$bar; // "somevar", simple variable variable
echo ${$bar}; // "somevar", complex syntax
echo ${bar}; // "var", because {bar} treated as a string constant:
// Notice: Use of undefined constant bar - assumed 'bar'
So, using variable variables syntax ${hello} simply translated to $hello.

Categories