括号的使用
Use of Brackets
我正在读一本关于 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)。
此外,具体参考第二个例子,我问自己为什么作者决定使用圆括号:这不是多余的吗?是为了提高易读性,还是有其他我想不到的原因?
这其实很简单。在字符串上下文中,例如用引号括起来时,当您需要像方法或 属性 一样解析对象属性时,您将其包裹在花括号中。
所以这可以帮助解释这个陈述:
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
我正在读一本关于 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)。
此外,具体参考第二个例子,我问自己为什么作者决定使用圆括号:这不是多余的吗?是为了提高易读性,还是有其他我想不到的原因?
这其实很简单。在字符串上下文中,例如用引号括起来时,当您需要像方法或 属性 一样解析对象属性时,您将其包裹在花括号中。
所以这可以帮助解释这个陈述:
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