0
<?php

abstract class AClass
{
    private $variable;
    public function __construct ()
    {
    
    }
    
    public function load($var)
    {
        $this->variable = $var;
        return $this;
    }
}

class BClass extends AClass
{
    public function out()
    {
    
    }
}

code A is

(new Bclass())->load($dummydata)->out();

And code B is

$dummy = new Bclass();
$dummy->load($dummydata);
$dummy->out();

I think it's the same.

But Undefined method 'out' error occurred in code A.

What's the difference?

AD7six
  • 63,116
  • 12
  • 91
  • 123
gafield
  • 1
  • 3
  • It's possible that `load` method doesn't return the object, so you can't chain after it. – IT goldman Jul 30 '22 at 14:03
  • How do I change the load method to use code A? – gafield Jul 30 '22 at 14:12
  • No change is required, its [not reproducible](https://onlinephp.io/c/e907a). The only thing you need to do to chain method calls is `return $this` - which the code is already doing. If you're seeing a problem you need to provide more details such as the exact error message (all of it please :)) and the version of php you are using. I've removed the tags not relevant to the question. – AD7six Jul 30 '22 at 14:24
  • You may find this question and answer helpful: [PHP method chaining or fluent interface?](https://stackoverflow.com/questions/3724112/php-method-chaining-or-fluent-interface) – AD7six Jul 30 '22 at 14:31

0 Answers0