-2

So I'm no expert with PHP and have been learning procedural since now, when I've decided to try out some OOP. I tried creating a MySQL escape function to prevent SQL injection, but the error "Fatal error: Cannot re-assign $this" gets spit out.

public function escape($result) {
        global $this->con;
        return mysqli_real_escape_string($this->con, $result);
}

When I remove "global", the error is no longer present but need such.

Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
  • Glogal assigns a variable to the global name space. I.e. outside your object, for everyone to use. $this references the current instance of your object. You can't make $this global, that would allow everyone to change con. Create an instance of your object and change the value of con of that instance in your code. – Nic3500 Oct 28 '17 at 18:39
  • 2
    That doesn't even make sense ... if you have access to `$this->con` in that scope, then you can pass it into `mysqli_real_escape_string` (still not using prepared statements ...?) as a parameter right there - doesn't have to be global for that at all. – CBroe Oct 28 '17 at 18:40
  • See this: https://stackoverflow.com/questions/1523479/what-does-the-variable-this-mean-in-php – Nic3500 Oct 28 '17 at 18:41

1 Answers1

1

Why are you using global and $this together?

global is assigning a variable with the given name from outside the scope.

For instance

$variable = 'test';
final class Test
{
    public function __toString()
    {
        global $variable;
        return $variable;
    }
}
echo new Test();

See how I can use $variable, while it has been assigned outside of the scope?

So when doing global $this, it tries to assign on $this, which can not be done.

If you are trying to do OOP code, you should definitely use PDO rather than mysqli though. Also, as said in the comments, use prepared statements.

Thomas Dutrion
  • 1,844
  • 1
  • 11
  • 9