0

Please have a look at the below example code. From that I have index, test_1 & test_2 functions.

If the index function's case-1 statements executed, I'm getting output 12. But case-2 statement getting the error Message: Call to a member function test_2() on null.

Can anyone help me to make the case-2 statement work?

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Debug extends CI_Controller
{
  public function index()
  {
    //case 1 : Working
    $this->test_1();
    $this->test_2();

    //case 2: Not Working
    echo $this->test_1()->test_2();     
  }

  function test_1()
  {
    echo "1";
  }

  function test_2()
  {
    echo "2";
  }
 } ?>

Thanks in advance..

3
  • 3
    In your functions you need return '$this'. Commented Jan 4, 2020 at 16:03
  • You cannot do that, that's why it's not working. For $this->test1()->test2() to work, test2() would need to be a method of test1() (which would need to be a class, not a method Commented Jan 4, 2020 at 17:03
  • @Dimitry Yes, That's working if I returned $this each of the functions this $this->test1()->test2(); call is working fine. Thanks for the answer Commented Jan 4, 2020 at 18:17

1 Answer 1

1

In order to achieve the $this->test1()->test2() call $this need to be returned in each of the functions.

Updated Code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Debug extends CI_Controller
{
  public function index()
  {
    //case 1 : Working
    $this->test_1();
    $this->test_2();

   //case 2: Working
   echo $this->test_1()->test_2();     
 }

 function test_1()
 {
   echo "1";
   return $this;
 }

 function test_2()
 {
   echo "2";
   return $this;
 }
} ?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.