php 字符串串联_JS / PHP字符串串联错误类型

php 字符串串联

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

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/jsphp-string-concatenation-mistype/

php 字符串串联

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值