Skip to content
Advertisement

PHP function working differently for return and echo. Why?

By using the following class:

JavaScript

and Calling the function, by the following code, it works fine.

JavaScript

But if in the SafeGuardInput class if I replace echo $finaloutput; with return $finaloutput; and then echo $forminput; on the index.php page. It DOES NOT WORK. Please provide a solution.

Advertisement

Answer

You can’t return anything from a constructor. The new keyword always causes the newly created object to be assigned to the variable on the left side of the statement. So the variable you’ve used is already taken. Once you remember that, you quickly realise there is nowhere to put anything else that would be returned from the constructor!

A valid approach would be to write a function which will output the data when requested:

JavaScript

Then you can call it like in the normal way like this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement