klewis
klewis

Reputation: 8350

PHP - understanding a basic class functionality

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!

Upvotes: 0

Views: 54

Answers (2)

Marc B
Marc B

Reputation: 360572

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.

Upvotes: 2

Adam
Adam

Reputation: 1264

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;
  } 

Upvotes: 2

Related Questions