0

I have a PHP code

<?PHP

  class options{
         public function A(){
              echo "Select A";
         }
         public function B(){
              echo "Select B";
         }
  }


 $opt = new options;

 $opt->B()->A();

?>

I need output

============

Select A Select B

===========

But I got the output

============

Select B Select A

===========

Please Solve my issue.

  • 1
    _“But I got the output”_ - not with that code you have shown, that should only get you “Select B” - and then a “Fatal error: Uncaught Error: Call to a member function A() on null in […]”. – CBroe Jun 03 '20 at 11:08
  • The basis for _method chaining_ to work in the first place, is that each method _returns_ the object instance. – CBroe Jun 03 '20 at 11:09

1 Answers1

0

You need to return class instance in each method. However you didn't specify detailed purpose of this class.

class Options
{
    public function A()
    {
        echo "Select A";
        return $this;
    }

    public function B()
    {
        echo "Select B";
        return $this;
    }
}

$opt = new Options;

$opt->A()->B();
Jsowa
  • 9,104
  • 5
  • 56
  • 60