0

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.

3
  • 2
    "It does not work" is not an adequate description of the problem, no matter how hard you hit capslock. Commented Jun 8, 2020 at 18:20
  • $finaloutput is only a local variable... unknown in the destructor Commented Jun 8, 2020 at 18:22
  • Got the point. Thanks for helping the noob. Commented Jun 8, 2020 at 18:33

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

In the public function getFinalOutput, $form remains undefined variable.

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.