Method chaining behavior

<?php 
class Tes
{
  private $name;
  public function __construct($name)
  {
  $this->name = $name;
  }
  public function append($string)
  {
  $this->name .= $string;
  }
}
class Test
{
  private $tes;
  public function add($name)
  {
  $tes = new Tes($name);
  $this->tes = $tes;
  return $tes;
     }
}
$test = new Test;
$test->add('Foo')->append('Baz');
var_dump($test);

I’m surprised to know that the Tes class which is inside Test class has a name FooBaz.
I think that it will just Foo because $test->add('Foo') evaluate first before append('Baz')

Is the returned object $tes a reference to $test->tes , so any change made to the returned object will also affect the property that has just been set ?

why? that’s exactly how it is coded. new Tes($name) created “Foo” and then you append (!) “Baz”. append() is not a method of Test, after all!

At first, I thought that using append() will not modify the Test class. I though it just modifies the object Tes that’s returned by the add() method. But, it also modifies the tes property of Test class. It seems to be a reference to the tes property of Test class.

of course. Objects are passed by reference: http://php.net/manual/en/language.oop5.references.php

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.