Skip to content
Advertisement

Using $this when not in object context in PHP

I don’t know why i’m getting this error: Fatal error: Uncaught Error: Using $this when not in object context in C:xampphtdocsappindex.php:19 Stack trace: #0 {main}

This is my index.php and where the error points out:

<?php 

require_once 'models/Request.php';

$req = new Request;

if(isset($_POST['submit'])){
    $data = [
        'reqBy' => $_POST['reqBy'],
        'off' => $_POST['off'],
        'prob' => $_POST['prob']
    ];

    echo "<pre>";
      print_r($data);
    echo "</pre>";

    if($this->req->addRequest($data)){ //This is the line where it points the error
        echo 'Sucess';
    }else{
        echo 'Something';
    }
}
?>

I’m kinda lost solving this for half a day, so i’m reaching out here

Advertisement

Answer

You are not inside instance of class to use $this. Try this, it will work

require_once 'models/Request.php';

$req = new Request;

if(isset($_POST['submit'])){
    $data = [
        'reqBy' => $_POST['reqBy'],
        'off' => $_POST['off'],
        'prob' => $_POST['prob']
    ];

    echo "<pre>";
      print_r($data);
    echo "</pre>";

    if($req->addRequest($data)){ //This is the line where it points the error
        echo 'Sucess';
    }else{
        echo 'Something';
    }
}
?>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement