Issue with chaing method object orientated

I am working in PHP object orientated.

And I am trying to chain a few method together and getting the following error

"Catchable fatal error: Object of class Try2 could not be converted to string"

What am I doing wrong?
indent preformatted text by 4 spaces

 <?php

class Try2{

public $temp;

 function one(){

$this->temp = 1;
return $this;


 }


 function two(){

  $this->temp += 1;
  return $this;
  


 }
 function there(){

  $this->temp += 1;
  return $this;
  


 }
}



$try2 = new Try2();

echo $try2->one()->two()->there();

you’re trying to echo, but return an object

var_dump($try2->one()->two()->there());
1 Like

I am trying to print on the screen the result of the chaining of the methods.

The output should be "3".

When I use your suggested var_dump.

I get the following unwanted result public ‘temp’ => int 3

please advise how I can get PHP to print "3".

when returning an object, access the property to print out it’s value

https://php.net/manual/en/sdo.sample.getset.php

Thank you for your answer.

However I’m not sure from your answer what do I need to change in my code in order to print “3” via a chaining mechanism.

In the object methods you are returning the object itself. So when echoing the return value of the method(s) you are echoing the object, not some property value inside the object.

Either echo the object property directly
echo $try2->one()->two()->there()->temp

or make the property private and make a getter for it
echo $try2->one()->two()->there()->getTemp()

Hi Jim,

Thank you for your answer it seems to work.

What I still do not understand if I make a return at the end of the statement should it not print the value of “temp”?

As that is what “return $this” is all about.

I am trying to learn from this example so if you can please explain to me a little bit more about the logic I will appreciate it.

return $this returns the actual object, not some value (an object can have many properties so what value would it select anyway?). The point of returning the object is to daisy chain method calls like you are doing.

If you make another method (ie getTempValue) that returns $this->temp then you could do
echo $try2->one()->two()->there()->getTempValue()

but since you would then be returning a value, not the object you could no longer chain method calls after calling that method. So this would not work
echo $try2->one()->two()->getTempValue()->there()

Thank you for your help.

Now I understand.

Sponsor our Newsletter | Privacy Policy | Terms of Service