tags:

views:

195

answers:

3

I get this error for the code below, what does it mean?

[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/

<?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";
}
+7  A: 

$this is a special variable in php. If this code is taking place inside a class, $this is a reference to the object the method is being invoked on. You cannot assign a new value to $this inside of a class. It is a limitation of PHP that you also cannot assign to a variable named $this outside of a class, where it would otherwise be valid to do so.

I believe this was valid in PHP4, but as of PHP5 You'll have to choose a new variable name.

meagar
Well, it isn't in a class, but thanks anyway, and also to the one above. He gets the check, however, because it apparently doesn't work outside a class either.
Arlen Beiler
No, as I said, it is a limitation of PHP. You cannot assign to `$this` in any context, inside of our outside of a class method.
meagar
Well, that came later. The other guy got it right the first time ;-) Thanks, anyway
Arlen Beiler
Actually, you didn't add it till after I left the comment and refreshed the page.
Arlen Beiler
+13  A: 

$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.

Oddthinking
+3  A: 

I'm not really a PHP expert, but i think $this is referring to the current object, so if you set this to null, you try to set the current object to nothing, wich can not work.

phimuemue