0

I'm having trouble to echo a result from a function within a function in the same class.

class className 
    {
         function first_function()
         {
             echo "Here it is: " . $this->second_function('test');
         }

         function second_function($string)
         {
             return $string;
         }
    }

That returns only:

Here it is:

Echoing the $string in my second_function() results in:

testHere it is:

Any suggestions? Thank you.

9
  • 1
    Hi, it's work. What you have error message? Commented May 19, 2016 at 14:11
  • what's your expected output? Commented May 19, 2016 at 14:11
  • I'm guessing it should echo Here it is: test ... and I can't immediately see a reason why it wouldn't. Commented May 19, 2016 at 14:12
  • @Iwan – no error messages. the second_function returns nothing... Commented May 19, 2016 at 14:13
  • 1
    It's normal behavior, if you echo $string in your second function, the second function is called before the result of the first is sent. However the result should be "testHere it is : test" Maybe you replace return with echo, which is not the right thing to do. Commented May 19, 2016 at 14:13

2 Answers 2

1

as @cherryTD mentioned, I did simplify the code. I see why it didn't work. Posting it here so it might help someone else. The second function is a recursive function and that didn't work:

function second_function($var,$cnt) {
    [database query]
    if(result) {
        $cnt++;
        $this->second_function($var, $cnt);
    } else {
        return $var;
    }
}

But this does work:

function second_function($var,$cnt) {
    [database query here]
    if(result) {
        $cnt++;
        return $this->second_function($var, $cnt);
    } else {
        return $var;
    }
}

A return was needed when calling the function from within itself.

so:

$this->second_function($var, $cnt);

had to be:

return $this->second_function($var, $cnt);

Thank you for the responses, everyone.

Sign up to request clarification or add additional context in comments.

Comments

0
class className 
    {
         function first_function()
         {
             echo "Here it is: " . $this->second_function('test');
         }

         function second_function($string)
         {
             return $string;
         }
    }


    $obj = new className();
   $a=  $obj->first_function();
   echo $a;

1 Comment

it's woking fine then what is the problem?

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.