Asked  7 Months ago    Answers:  3   Viewed   37 times

here is the part if having error.

Fatal error: Using $this when not in object context in /pb_events.php on line 6

line 6 is: $jpp = $this->vars->data["jpp"];

function DoEvents($this) {

    global $_CONF, $_PAGE, $_TSM , $base;

    $jpp = $this->vars->data["jpp"];

    $cache["departments"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_departments]}");
    $cache["locations"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_location]}");
    $cache["names"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_names]}");
    $cache["categories"] = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[job_categories]}");

Thanks a lot! appreciate!

 Answers

34

$this only makes sense in methods, not in functions

this is ok

class Foo {
     function bar() {
          $this->...

this is not

function some() {
    $this->

// edit: didn't notice he passes "$this" as parameter

advice: simply replace "$this" with "$somethingElse"

Wednesday, March 31, 2021
 
JohnnyW
answered 7 Months ago
34

$this will not be available in a static function. You'll probably want to re-create $app within the static function:

static function store($key, $value)
{
    $app = base_url('application') . '/cache/';
    $key = sha1($key);
    $value = serialize($value);
    file_put_contents( $app . $key.'.cache', $value);
}

I'm not quite sure what you're trying to do in the grand context of your application, but you may not even need a static method in the first place.

Wednesday, March 31, 2021
 
OMGKurtNilsen
answered 7 Months ago
48

Like the error says, you can't use $this outside of the class definition. To use $_db outside the class definition, first make it public instead of private:

public $_db

Then, use this code:

$authDb = new AuthDb();
$authDb->_db->prepare($query); // rest of code is the same

--

You have to understand what $this actually means. When used inside a class definition, $this is used to refer to an object of that class. So if you had a function foo inside AuthDB, and you needed to access $_db from within foo, you would use $this to tell PHP that you want the $_db from the same object that foo belongs to.

You might want to read this StackOverflow question: PHP: self vs $this

Thursday, August 5, 2021
 
Codex
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :