0

I am reading a book about PHP and Object Oriented Design. I've found some code samples about the way the author uses the brackets that puzzles me a little. I let you a pair of samples below:

First sample:

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

Second sample:

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

All I know about print construct, is that brackets around the arguments are not required (http://php.net/manual/en/function.print.php).

Furthermore, with specific reference to the second example, I'm asking myself why has the author decided to use even round brackets: wouldn't it be redundant? Is it just intended to improve legibility, or is there any other reasons I cannot imagine?

  • the curly brackets are required as soon as the variable to be expanded inside of the double-quoted string is anything more complicated than **$variable** – Calimero Oct 02 '17 at 10:16

1 Answers1

1

This is pretty simple actually. Inside a string context, like when wrapped in quotes, when you need to parse an object attribute like a method or property you wrap it inside curly braces.

So this can help explain the statement: print "Author: {$product->getProduct()};

Now second example is just an extension of the first one, where the author has used multiple lines and round brackets for readability. It can be also written as:

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

Here supposing we had following values:

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

Then if we had echoed $b after the assignments above we would get:

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

raidenace
  • 12,789
  • 1
  • 32
  • 35