0

I tried calling multiple functions on a single object. But I got this error

Uncaught Error: Call to a member function dordor()

Could you correct me please?

<?php

class Das
{
    public $a= 'mulut';
    public $b = 'anda';
    public $c = 'kotor';

    public function dor(){
        echo $this->a.PHP_EOL;
        echo $this->b.PHP_EOL;
        echo $this->c.PHP_EOL;
        echo PHP_EOL;
    }

    public function dordor(){
        echo 'lmao';
        echo PHP_EOL;
    }
}

$s = new Das();
$s->a = 'mulut';
$s->b = 'anda';
$s->c = 'kotor';
$s
->dor()
->dordor();

?>
yunluo
  • 13
  • 1
  • i tried to write like this , $s->dor()->dordor(); but it still give me error – yunluo Apr 16 '20 at 08:56
  • 2
    You need to make your methods return themselves, so at the end of `dor()` you need a return value that is the object. Therefore `return $this;` will allow the outcome of the method `dor()` to then be chained along to the next method in the series, `dordor()` – Martin Apr 16 '20 at 09:01
  • If you write `echo gettype($s->dor());` you see that the type of `$s->dor()` is NULL and you are passing a NULL value to the class method `dordor()`, and that is the reason you are getting that error. Tell us what you exactly want to do. – MathCoder Apr 16 '20 at 09:12
  • i learn coding by self-taught, and i just wanna write the code to make it look neat. – yunluo Apr 16 '20 at 09:20

2 Answers2

0

You are using a method as an object. $s->dor()->dordor(); But dor() is not an object and it is a method. you have to add $this->dordor(); at the end of your dor() method codes which is call dordor() method with same object that you called dor() method. This:

<?php

class Das
{
    public $a= 'mulut';
    public $b = 'anda';
    public $c = 'kotor';

    public function dor(){
        echo $this->a.PHP_EOL;
        echo $this->b.PHP_EOL;
        echo $this->c.PHP_EOL;
        echo PHP_EOL;
        $this->dordor();
    }

    public function dordor(){
        echo 'lmao';
        echo PHP_EOL;
    }
}

$s = new Das();
$s->a = 'mulut';
$s->b = 'anda';
$s->c = 'kotor';
$s->dor();

?>
0

What you want to implement, if I have understood you correctly, is often called "chaining".

To implement this you have to return the object itself, i.e. "this", at the end of your method.

I have adapted your code accordingly

    <?php

class Das
{
    public $a= 'mulut';
    public $b = 'anda';
    public $c = 'kotor';

    public function dor(){
        echo $this->a.PHP_EOL;
        echo $this->b.PHP_EOL;
        echo $this->c.PHP_EOL;
        echo PHP_EOL;
        return $this;
    }

    public function dordor(){
        echo 'lmao';
        echo PHP_EOL;
        return $this;
    }
}

$s = new Das();
$s->a = 'mulut';
$s->b = 'anda';
$s->c = 'kotor';
$s
->dor()
->dordor();

?>
MThiele
  • 387
  • 1
  • 9