Cannot re-assign $this?

2019-05-17 22:00发布

I have a script on a server that had php version 4. Now it is changed to php5 and the script does not function any more. I get this error:

Fatal error: Cannot re-assign $this in URL database.php line 88

In the file is a class that has a function. Inside is the line 88:

$this = new $db( $serv, $user, $pass, $dbName );

What does the error mean and how can I change it?

标签: php message php4
6条回答
萌系小妹纸
2楼-- · 2019-05-17 22:10

$this is a predefined variable in PHP.

Here's the reference in the PHP manual: Classes and Objects: The Basics. It describes how, inside a method, $this points to "this object" that is being operated upon. It is still reserved outside a method, though.

Change the identifier to another word.

查看更多
\"骚年 ilove
3楼-- · 2019-05-17 22:12

$this is a special "variable" that always refers to the object the current function is executing in. It only makes sense inside functions that belong to a class; however, you are not allowed to use it anywhere else, and you may never assign to it. The solution is simply to rename the variable.

查看更多
戒情不戒烟
4楼-- · 2019-05-17 22:12

The class is attempting to re-define itself ($this in php is the same as this in C#) and it can't be done. You should change $this to something else and the error should be gone then.

查看更多
该账号已被封号
5楼-- · 2019-05-17 22:12

$this is a reserved variable name and cannot manually be assigned a value.

查看更多
Summer. ? 凉城
6楼-- · 2019-05-17 22:22

You can use refrences trick:

$thisRef = &$this;
$thisRef = new $db($serv, $user, $pass, $dbName);
查看更多
smile是对你的礼貌
7楼-- · 2019-05-17 22:33

You can reassign $this value by variable variable

$name = 'this';
$$name = 'stack';
echo $this;

// this will result stack

查看更多
登录 后发表回答