phppsr-2psr-12

Is it necessary to put space after $this keyword in OOP PHP according to PSRs?


I studied PSR-2 and PSR-12 documentations completely but didn't find any explanation regarding whether to put any space after $this keyword.

My exact question is which one of following styles is more correct according to PSRs:

return $this->name;

or

return $this -> name;

sample codes to compare would be as below:

class Car
{
    public $name;
    public function getName()
    {
        return $this->name; // I've always seen this style (no spaces)
    }
}

in comparison with:

class Car
{
    public $name;
    public function getName()
    {
        return $this -> name; // Includes spaces
    }
}

Are both correct? If so, is there a reason to use one over the other?


Solution

  • Both are permitted by the standards.

    Having "spaces" around the object operator (->) is not forbidden by any of the PSR standards. And it's legal.

    Whitespace around this is not regulated simply because sometimes when writing fluent interfaces it can make sense to separate the chained calls with whitespace. E.g.:

    $foo->bar()
        ->baz()
        ->fizz()
        ->fizzBuzz();
    

    And forbidding this would make not particular sense.

    While additional language could have been added to account for this and other cases, it wasn't. Maybe it wasn't considered by the commitee, maybe it was considered a given that the common practice of the PHP community would prevail without needing an additional standard. Why they wouldn't add this specific language is not particularly important.

    However, your example of using whitespace like this:

    $foo -> bar();
    

    Simply difficults reading and provides no advantage. While not illegal, and not against the coding style PSRs, it's simply a bad idea.