致命错误:不在对象上下文中使用$this不能正常工作


Fatal error: Using $this when not in object context no working properly

<?php
class Functions {
    public static function extendSql($dbhost, $dbuser, $dbpass, $dbname) {
        // making the mysql connection dynamically editable
        $mysql_connect  =   mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: " . mysql_error());
        $mysql_select_db =  mysql_select_db($dbname) or die(mysql_error());
    }
    public static function whileLoop($dbuser, $dbpass, $dbname, $sql, $passedData) {
        $this->extendSql($dbuser, $dbpass, $dbname);
        $results = mysql_query($sql);       
        while ($row = mysql_fetch_array($results)) {
        echo $passedData;
        }
    }
}
Functions::whileLoop("root", "", "rand", "SELECT * FROM products",
$hello = "hi all");
?>
当我执行上面的代码时,我得到以下错误:

致命错误:当不在对象上下文中使用$this时C:'Workspace'htdocs'Misc-2'nurbell1'core'conf'misc.php on line 13

我做错了什么?显然,在我的代码中,$this是在类的上下文中引用的。

您在静态函数中使用$this,该函数不属于当前实例/上下文,因此无法使用$this

您正在静态函数中调用this。只有在拥有Function类的对象时才能使用this。必须使用self关键字才能访问静态函数。

将代码改为self::extendSql($dbuser, $dbpass, $dbname);

请阅读本手册了解self关键字

您不能在静态方法中使用$this,因为$this指向对象而不是类,并且您不能保证在调用静态方法时拥有对象。相反,你可以使用"self::method()"从同一个类中调用静态方法。

你应该读一下PHP的OOP是如何工作的:PHP中的OO以及类和对象的区别是什么