snapsvg

2013-03-28

Cannot reassign $this?

PHP won't let you reassign $this because it is a readonly reference to the contextual object.


class Test {
    var $foo = "bar";

    function abc() {
        $this = "Hello!";
    }
}

$test = new Test();
$test->abc();

PHP Fatal error:  Cannot re-assign $this in - on line 14

Fatal error: Cannot re-assign $this in - on line 14

Since PHP has the flaw of allowing you to use variables as variables, however, you can put 'this' in a variable. PHP doesn't seem to notice that that's assigning to $this:


class Test {
    var $foo = "bar";

    function abc() {
        $thisStr = "this";
        $$thisStr = "Hello!";
    }
}

$test = new Test();
$test->abc();

Tricked you!


However, if you then use $this as an object, it's still $this! But if you don't, it's not:


class Test {
    var $foo = "bar";

    function abc() {
        var_dump($this);
        var_dump($this->foo);

        $thisStr = "this";

        $$thisStr->foo = "cats";

        $$thisStr = "Hello!";

        var_dump($this);
        var_dump($this->foo);
    }
}

$test = new Test();
$test->abc();

class Test#1 (1) {
  public $foo =>
  string(3) "bar"
}
string(3) "bar"
string(6) "Hello!"
string(4) "cats"

Surely someone's realised by now that the people behind PHP might not really know what they're doing.


Edit: turns out this already came from reddit

1 comment:

  1. You ought to take part in a contest for one of the most useful websites on the net. I'm going to recommend this website!

    ReplyDelete