0

If I have the following PHP class example setup...

class foo {
  public $x = 2;

  public function getX() {
    return $this->x;
  }

  public function setX($val) {
    $this->x = $val - $this->x;
    return $this;
  } 
}

$X = (new foo)->setX(20)->getX();

How comes I need the ->getX(); part on the end of the object initiation process in order to get 18? How come I simply can't hide the public getX() function and write...

$X = (new foo)->setX(20);
echo $X; // and show 18 without errors.

Instead it throws an error and says...

Catchable fatal error: Object of class foo could not be converted to string in C:\...

Is not $this->x refering to public $x = 2? I guess I'm a little confused why we're depending on Public function getX(). Thanks in advance for help understanding!

2 Answers 2

2

Because your returning an instance of the class foo when you do return $this;. If you want it to work as above then you need to return $x as shown below:

  public function setX($val) {
    $this->x = $val - $this->x;
    return $this->x;
  } 
Sign up to request clarification or add additional context in comments.

Comments

2

echo $X tries to output the object. But your object doesn't have the magic method __toString() so PHP has no way of knowing exactly WHAT to output when the object is used in a string context.

e.g. if you added this to your object definition:

public function __toString() {
   return $this->getX();
}

you'd "properly" get 18 when you do echo $X.

1 Comment

Thank you Marc B, I will add that to my knowledge now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.