DEV Community

Discussion on: 11 Most Asked Questions About PHP

Collapse
 
_garybell profile image
Gary Bell

It's also worth mentioning that for "6. When to use self over $this?", that you have to use self as the return type of a class function (PHP 7.4+) when you are declaring the return types, and returning the full class object (for things like method chaining). e.g.

class Person {
  private string $name = '';
  function getName(): string
  {
    return $this->name;
  }

  function setName(string $name): self
  {
    $this->name = $name;
    return $this;
  }
}

This would allow you to do mad stuff like:

$person = new Person();
$person->setName('Bill')->setName('Ben')->setName('Sally')->setName('Betty');
echo $person->getName(); // outputs Betty

If you don't want to do method chaining, you don't have to return $this from setName(), but self is used as the return type, when performing return $this within a function