0

我正在阅读一本关于面向对象的 PHP 的书,并注意到作者在某些情况下使用了复杂的语法。在关于继承的章节中,他使用了以下代码:

// Declare the getSummaryLine() method
function getSummaryLine() {
// Define what the getSummaryLine() method does
     $base  = "$this->title ( {$this->producerMainName}, ";
     $base .= "{$this->producerFirstName} )";
     return $base;
}

我的问题是,你为什么不直接使用:

// Declare the getSummaryLine() method
function getSummaryLine() {
// Define what the getSummaryLine() method does
     return "$this->title ( $this->producerMainName, $this->producerFirstName )";
}

因为两者似乎都返回相同的东西?

如果这很明显,请原谅我。我已经阅读了手册中的 PHP 复杂语法,但它并没有让我更清楚。是安全问题、风格选择还是其他问题?

4

3 回答 3

2

They both achieve the same thing, but the reason for the compounded statement has to do with readability. Longer concatenated strings are simply easier to read, and is nothing more than a code flavour on the authors part.

The complex bit about this has to do with evaluation. Using curly braces you can do this:

echo "This works: {$arr['key']}";
于 2012-11-25T18:20:02.813 回答
2

In this case, it's only a matter of style/preference.

The author may feel it's easier to read when it's spread out accross multiple lines and variables are inside curly braces.

于 2012-11-25T18:20:24.327 回答
1

所有这些都是有效的。

作者可能只是为了可读性而使用连接,长行代码在书中也不太好。

在嵌入双引号时,您有时需要在数组/对象中的字符串周围使用 {},否则您会看到语法错误。

// Declare the getSummaryLine() method
function getSummaryLine() {
// Define what the getSummaryLine() method does
     $base  = "$this->title ( {$this->producerMainName}, ";
     $base .= "{$this->producerFirstName} )";
     return $base;
}

或者

// Declare the getSummaryLine() method
function getSummaryLine() {
// Define what the getSummaryLine() method does
     return "{$this->title} ( {$this->producerMainName}, {$this->producerFirstName} )";
}

或者

// Declare the getSummaryLine() method
function getSummaryLine() {
// Define what the getSummaryLine() method does
     return $this->title.'( '.$this->producerMainName.', '.$this->producerFirstName.' )';
}
于 2012-11-25T18:27:06.420 回答