Skip to content
Advertisement

PHP function working differently for return and echo. Why?

By using the following class:

class SafeGuardInput{

    public $form;
    public function __construct($form)
    {
        $this->form=$form;
        $trimmed=trim($form);
        $specialchar=htmlspecialchars($trimmed);
        $finaloutput=stripslashes($specialchar);
        echo $finaloutput;
    }

    public function __destruct()
    {
        unset($finaloutput);
    }
}

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

        <?php 
        require('source/class.php');
        $target="<script></script><br/>";
        $forminput=new SafeGuardInput($target);
        ?>

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:

class SafeGuardInput{

    public $form;
    public function __construct($form)
    {
        $this->form=$form;
    }

    public function getFinalOutput()
    {
        $trimmed = trim($this->form);
        $specialchar = htmlspecialchars($trimmed);
        $finaloutput = stripslashes($specialchar);
        return $finaloutput;
    }
}

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

$obj = new SafeGuardInput($target);
echo $obj->getFinalOutput();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement