I was looking through some code for work, and came across this line:
eval("$element = \"$element\";");
I’m really confused as to why any PHP developer would’ve written this line. What purpose does this serve, besides setting a variable to itself?
Luckily, the function this line is in is never called.
<?php $string = 'cup'; $name = 'coffee'; $str = 'This is a $string with my $name in it.'; echo $str. "\n"; eval("$str = \"$str\";"); echo $str. "\n"; ?>
The above example will output:
This is a $string with my $name in it. This is a cup with my coffee in it.
I do just ctl+c ctrl+v 🙂
It converts the value of the variable to a string, but I wouldn’t recommend using it.
Use the function
strval() instead. Have a look at the manual.
This assigns the string-converted contents of the variable
$element to a variable called
$element. Another way to do this is to use
strval, or in some cases
It doesn’t really do much except converting the value to string or might serve as a poor alternative to
sprintf. But if the variable contains double quotes, this is gonna cause some trouble. You really wouldn’t want to eval a code like this:
$element = 'foo"bar';
Not to mention some even more harmful code. Seems like a place for a “php injection” 😀
Don’t use it.