Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Why do different versions of PHP return different results when I use $this as a dynamic variable in isset()?

In PHP 7.0:

$a = 'this';
return isset( $$a );
// returns true

But in PHP 7.1:

$a = 'this';
return isset( $$a );
// returns false

Does anyone know why this happens?

like image 257
Moein Pakkhesal Avatar asked Jun 25 '18 11:06

Moein Pakkhesal


Video Answer


1 Answers

This is related to this change in 7.1:

Inconsistency fixes to $this

Whilst $this is considered a special variable in PHP, it lacked proper checks to ensure it wasn't used as a variable name or reassigned. This has now been rectified to ensure that $this cannot be a user-defined variable, reassigned to a different value, or be globalised.

http://php.net/manual/en/migration71.other-changes.php#migration71.other-changes.inconsistency-fixes-to-this

This RFC explains it in more detail, though it also says:

Disable ability to re-assign $this indirectly through $$

An attempt to re-assign $this through $$ assignment will lead to throwing of Error exception.

$a = "this";
$$a = 42; // throw new Error("Cannot re-assign $this")

It's still possible to read $this value through $$.

(Emphasis mine.)

isset seems to have its own special treatment of $$ for $this which prohibits it from seeing it. I'm not sure if that's intentional or a byproduct of these changes.

like image 182
deceze Avatar answered Sep 18 '22 13:09

deceze