-3

Recently I was setting up a symfony application where I've had to make some entitys. To create those Entitys I used the symfony console and ran the make:entity script.

This then asked me, if I want to add some fields. And of course I just added my Attributes using this function because it was easy to use. Then it automatically created my attributes with the matching doctrine Annotations and the getters and setters. Here's a small example:

 /**
 * @ORM\Column(type="string", length=254)
 */
private $attr1;

/**
 * @ORM\Column(type="integer")
 */
private $attr2;

/**
 * @ORM\Column(type="boolean")
 */
private $attr3;

public function getAttr1(): ?string
{
    return $this->attr1;
}

public function setAttr1(string $attr1): self
{
    $this->attr1 = $attr1;
    return $this;
}

public function getAttr2(): ?int
{
    return $this->attr2;
}

public function setAttr2(int $attr2): self
{
    $this->attr2 = $attr2;
    return $this;
}

public function getAttr3(): ?bool
{
    return $this->attr3;
}

public function setAttr3(bool $attr3): self
{
    $this->attr3 = $attr3;
    return $this;
}

Now, my question is what those ?string || ?int ||?bool || self mean. Do they like tell the function to expect to return a string and what does the self tells the function? I just got a little confused by this, because I've never seen such a thing in php untill now. (attention newbie-alert)

gp_sflover
  • 3,460
  • 5
  • 38
  • 48

3 Answers3

1

Those are parameters types (inputs and outputs).

  • ? - it allows to pass null to/from method.
  • self - it means that method will return its object.
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
bigwolk
  • 418
  • 4
  • 17
1

It used to notice the output type of the method since php 7, you can get more informations here

The ? mean than the output type can be null, and the self is the same type of the current class.

user7867717
  • 285
  • 3
  • 15
0

Self means it return instace of this class. Its called "fluent setters". With that, you can chain-call methods. Eg:

$someObj->setId(1)
    ->setNum(5)
    ->setOtherAttr('string');
Eakethet
  • 682
  • 1
  • 5
  • 18