解释器如何知道双引号变量何时结束


How does the interpreter know when a double quoted variable ends?

我使用的代码有效:

$this->path_medium = $this->PICTURES . "$this->file_hash-2.jpg";

然而,我需要更新它,因为它不是很可读;

$this->file_hash

是一个变量。

-2.jpg

是我附加到变量的字符串。

解释器如何知道变量的结尾和字符串的开头。

解释器如何知道变量的结尾和字符串开始。

变量不包含(-)字符。比如(echo "$var-$var";),那么PHP在这种情况下将file_hash视为变量。

发件人http://www.php.net/manual/en/language.variables.basics.php

变量名称遵循与PHP中其他标签相同的规则。有效的变量名以字母或下划线开头,后跟任意数量的字母、数字或下划线。作为常客表达,则表示为:'[a-zA-Z_''x7f-''xff][a-zA-Z0-9_''x7f-''xff]*'

代码按原样运行的原因是-不是变量名中的有效字符。PHP在遇到无效变量名字符的边界处停止解析变量名。如果你尝试过这样做:

$this->path_medium = $this->PICTURES . "$this->file_hash2.jpg";

PHP会认为$this->file_hash2是被引用的变量。

有几种方法可以解决这个问题。我个人的偏好是完全不把变量括在引号里,就像这样:

$this->path_medium = $this->PICTURES . $this->file_hash . '-2.jpg';

为了可读性,您也可以在变量周围使用{}

$this->path_medium = $this->PICTURES . "{$this->file_hash}-2.jpg";

尝试:

$this->path_medium = $this->PICTURES . $this->file_hash . "-2.jpg";

此外,我如何更新它,以便更清楚?

将curlies包裹在变量周围:

$this->path_medium = "{$this->PICTURES}{$this->file_hash}-2.jpg";

(或者使用串联,就像您对第一个变量所做的那样)

口译员如何了解

我假设它将停止在变量的第一个无效字符处(-就是其中之一)

语法不正确,将变量插入字符串中,因此必须使用@Sean代码,否则编译器无法"拆分"变量文本。