括号的使用[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在读一本关于PHP和面向对象设计的书。我找到了一些关于作者使用方括号的方式的代码示例。我在下面给你一对样品:

第一个样本:

print "Author: {$product->getProduct()};

第二个样本:

$b = "{$this->title} ( {$this->producerMainName}, ";
$b .= "{$this->producerFirstName} )"; 
$b .=  ": page count - {$this->nPages}"; 

我所知道的print构造,是不需要围绕参数的括号(http://php.net/manual/en/function.print.php)。

此外,特别参考第二个例子,我问自己为什么作者决定使用圆括号:它不是多余的吗?它只是为了提高易读性,还是有其他我无法想象的原因?

php syntax brackets
1个回答
1
投票

实际上这非常简单。在字符串上下文中,就像用引号括起来一样,当你需要解析像方法或属性这样的对象属性时,你将它包装在花括号中。

所以这有助于解释声明:print "Author: {$product->getProduct()};

现在,第二个示例只是第一个示例的扩展,其中作者使用多行和圆括号来提高可读性。它也可以写成:

$b  = "{$this->title}"; 
$b .= "({$this->producerMainName},{$this->producerFirstName})";
$b .= ": page count - {$this->nPages}";

这里假设我们有以下值:

$this->title = "Author Details ";
$this->producerMainName = "Doe";
$this->producerFirstName = "John";
$this->nPages = 10;

然后,如果我们在上面的任务之后回应了$b,我们会得到:

Author Details (Doe,John): page count - 10

© www.soinside.com 2019 - 2024. All rights reserved.