php 字符串串联
Another one from the "this is not a syntax error" department.
来自“这不是语法错误”部门的另一个部门。
The front-end developer is a strange beast who has to jiggle to and fro and code in several languages literally at the same time - javascript, html, css, php or some other server side language, some SQL dialect... No wonder that sometimes we make silly mistakes like:
前端开发人员是一个奇怪的野兽,他必须同时来回晃动并使用多种语言进行编码-javascript,html,css,php或某些其他服务器端语言,某些SQL方言...难怪那个有时我们会犯一些愚蠢的错误,例如:
var $myarray;
var array = array();
$myarray = [];
foreach(var i in myarray)
Last night I just did a silly mistake like this. In JavaScript I used the PHP way of concatenating strings. Something like:
昨晚我只是犯了一个愚蠢的错误。 在JavaScript中,我使用了PHP串联字符串的方式。 就像是:
var user = 'Stoyan';
alert('hello ' . user);
This is obviously wrong, but the thing is that it's not a syntax error as one might expect. It alerts "undefined". Why is that?
这显然是错误的,但事实是,这并不是人们所期望的语法错误。 它警告“未定义”。 这是为什么?
Well, 'hello' is a string object. You can call methods and properties on it, like:
好吧,“ hello”是一个字符串对象。 您可以在其上调用方法和属性,例如:
>>> 'hello'.toUpperCase()
"HELLO"
>>> 'hello'.length
5
And spaces don't matter...
空间也不重要...
>>> 'hello' . length
5
>>> 'hello' . toUpperCase()
"HELLO"
So 'hello' . user
is an attempt to access the "user" property of the string object 'hello'. This property doesn't exist, hence the "undefined" result.
所以'hello' . user
'hello' . user
是尝试访问字符串对象“ hello”的“ user”属性。 该属性不存在,因此结果为“未定义”。
Doing the opposite (using JavaScript-type concatenation in PHP) is also not an error:
进行相反的操作(在PHP中使用JavaScript类型的串联)也不是错误:
$user = 'Stoyan';
echo 'Hello ' + $user; // prints 0
Tell your friends about this post on Facebook and Twitter
在Facebook和Twitter上告诉您的朋友有关此帖子的信息
翻译自: https://www.phpied.com/jsphp-string-concatenation-mistype/
php 字符串串联