我正在读一本关于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)。
此外,特别参考第二个例子,我问自己为什么作者决定使用圆括号:它不是多余的吗?它只是为了提高易读性,还是有其他我无法想象的原因?
答案 0 :(得分: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