代码之家  ›  专栏  ›  技术社区  ›  Arlen Beiler

PHP致命错误:无法重新分配$this

php
  •  7
  • Arlen Beiler  · 技术社区  · 14 年前

    我从脚本中得到这个错误:

    [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";
    }
    
    4 回复  |  直到 8 年前
        1
  •  23
  •   user229044    11 年前

    $this 是PHP中的预定义变量。

    以下是PHP手册中的参考: Classes and Objects: The Basics . 它描述了在一个方法中,$this如何指向正在操作的“this object”。但是,它仍然保留在方法之外。

    将标识符更改为另一个单词。

        2
  •  11
  •   user229044    14 年前

    $this 是PHP中的一个特殊变量。如果此代码发生在类中, $此 是对正在调用方法的对象的引用。不能将新值赋给 $此 在类中。这是PHP的一个限制,您也不能将它赋给名为 $此 在类之外,否则这样做是有效的。

    我相信这在php4中是有效的,但是在php5中,您必须选择一个新的变量名。

        3
  •  3
  •   phimuemue    14 年前

    我不是真正的PHP专家,但我认为 $this 是指当前对象,因此如果设置 this null ,您试图将当前对象设置为“无”,wich无法工作。

        4
  •  1
  •   Mistalis    8 年前

    您可以重新分配 $this 变量值

    $name = 'this';
    $$name = 'stack';
    echo $this;
    // this will result stack