简体   繁体   中英

PHP echo a returned value from another function in the same class

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.

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM