Search code examples
phpecho

PHP - Is there a way to echo text where the echo is?


So basically what I'm trying to do call a function in my main PHP page from a .php file which is just for processing data. That function basically calls echo. I want to call that function in a way that it really echoes where it sits, not where it is called from. Is there a way to do this?

php in index.php:

<?php
   function writeNot($text) {
       echo '<script type="text/javascript">',
       "addNotification(\"$text\");",
       '</script>';
   }
?>

php in process.php:

writeNot('The file has been successfully uploaded!');

I expect that the function echoes the HTML (which calls some Js) into the index.php, but what I assume is that it echoes into the process.php file, which I don't really want.


Solution

  • Use return instead of echo

       <?php
       function writeNot($text) {
           return'<script type="text/javascript">',
           "addNotification(\"$text\");",
           '</script>';
       }
    ?>
    

    Then use echo to print out the string that is returned from the function

    echo writeNote($text);
    

    And you should call the function inside index.php to execute it