PHP Fatal error: $ this cannot be reassigned

I get this error from my script:

[Fri Apr 23 10:57:42 2010] [error] [client 10.0.0.1] PHP Fatal error: Cannot re-assign $this in C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs\\abp\\fol\\test.php on line 27, referer: http://abp.bhc.com/fol/ 

Here is the code that causes the error:

 <?php $voiceboxes = array( '141133' => array( 'title' => 'Title', '1' => array( 'Title' => 'Title2', 'Link' => 'http://...', ), '12' => array( 'Title' => 'Title3', 'Link' => 'http://...', ) ), '1070453' => array( 'title' => 'Title4', '1' => array( 'Title' => 'Title5', 'Link' => 'http://...', ) ) ); $last = 0; //$this = 0; echo "<ol>\n"; foreach ($voiceboxes as $key => $value) { $last = 0; $this = null; //Error is thrown here, Line 27 //$voiceboxes[$key]['title'] echo "<ol>\n"; foreach ($value as $key2 => $value2) { if ($key2 == 'title') { echo "<li>$value2</li>\n"; } else { $this = (int) $key2; if ($this == $last + 1) { echo '<li>'; } else { '<li value="' . $key2 . '">';} $last = $key2; echo $voiceboxes[$key][$key2]['Title'] . "<br/>" . $voiceboxes[$key][$key2]['Link'] . '</li>' . "\n"; } } echo "</ol>\n"; } 
+6
php
source share
4 answers

$this is a predefined variable in PHP.

Here's a link in the PHP manual: Classes and Objects: Fundamentals . It describes how, inside the $ method, points to "this object" that it is working on. However, it is saved outside the method.

Change the identifier to another word.

+22
source share

$this is a special variable in php. If this code occurs inside a class, $this is a reference to the object to which the method is being called. You cannot assign a new value to $this inside a class. This is a PHP restriction that you also cannot assign to a variable named $this outside the class, otherwise it would be true for that.

I believe this was true in PHP4, but with PHP5 you will need to select a new variable name.

+11
source share

I am not a PHP expert, but I think $this refers to the current object, so if you set this to null , you are trying to set the current object to nowhere that cannot work.

+3
source share

You can reassign the value of $this variable variable

 $name = 'this'; $$name = 'stack'; echo $this; // this will result stack 
+1
source share

All Articles