开发者

The difference between these two...?

开发者 https://www.devze.com 2023-03-15 08:13 出处:网络
F开发者_高级运维irst time I searched for how to connect to databases with PHP I\'ve stumbled upon this example:

F开发者_高级运维irst time I searched for how to connect to databases with PHP I've stumbled upon this example:

mysql_connect("$host", "$username", "$password");

But what's the difference between that and this?

mysql_connect($host, $username, $password);


"$var" is complete nonsense. That's a string with the value of $var substituted. If the string doesn't contain anything but $var, it's identical to $var:

$var = "foo";
$nonsense = "$var"; // → "foo"

"$var" == $var. Use the $var as is, no need to wrap it in a string. It's faster, too.


The only difference is that in the first line PHP needs to process the strings and checks if there are variables menitioned in them and replace the variables with their respective values.

You can read more about this here:

http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

Edit

But as mentioned, the output will be the same.


No difference form user perspective actually. The variable-in-double-quote will be evaluated, so;

$hello="world";
$world="hello"; 
echo "$hello $world"

will print "world hello".

This feature allows you to do

"$very $annoying $string" instead of $very." ".$annoying." ".$string

This is like shell script (if you're familiar with shell script).


The result of it will be exactly the same! So don't worry about it. But if you should choose between them, you should choose the second.


$var = "World"
echo "Hello $var" // Output "Hello World"
echo 'Hello $var' // Output "Hello $var"

Double quotes replace variable content.

If you have an array you have to do something more:

$var = array("World")
echo "Hello {$var[0]}" // Output "Hello World"

Note the angle brackets {} betwenn $var[0]


There is no difference in terms of result unless , in the second one is not of datatype string.

The first one "$string" in php is parsed to get "valueofstring". PHP eliminates the strain for concatinating strings when you have to insert a string literal.

"something" . $string . "somethingelse" 
"something{$string}somethingelse"

both are the same.

For clarity in longer strings it is adviced you use with the braces {} as "{$string}".


the first your just passing the strings to the connection as if $username was your actual username, the latter your passing the value of the variable $username which will equal what has been set at an earlier time with $username = "myUsername"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号