Michael Grigsby
Michael Grigsby

Reputation: 12163

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");
?>

I get the following error when I execute the above code.

Fatal error: Using $this when not in object context in C:\Workspace\htdocs\Misc-2\nurbell1\core\conf\misc.php on line 13

What am I doing wrong? Obviously, $this is referenced inside the classed context in my code.

Upvotes: 0

Views: 1078

Answers (3)

liquorvicar
liquorvicar

Reputation: 6106

You can't use $this inside static methods as $this refers to the object rather than the class and you can't guarantee you have an object when a static method is called. Instead you can use "self::method()" to call a static method from within the same class.

You should read up on how PHP OOP works: OO in PHP and also what the difference between classes and objects is: difference between object and class

Upvotes: 1

robert
robert

Reputation: 8717

You are calling this within a static function. You can use this only when you have an object of the class Function. You have to use self keyword to access static functions.

Change your code to self::extendSql($dbuser, $dbpass, $dbname);

Please read this manual for more info on self keyword

Upvotes: 1

Kolky
Kolky

Reputation: 2977

You are using $this in a static function, which doesn´t belong to the current instance/context, and thus is unable to use $this.

Upvotes: 1

Related Questions