2

I don't know why i'm getting this error: Fatal error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\app\index.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

1
  • 1
    You can use $this only inside classes. The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). Commented Sep 21, 2018 at 8:20

3 Answers 3

3

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';
    }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

You should use $req->addReques insted of $this->req->addReques

Comments

1

You canjust use your instance;

<?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($req->addRequest($data)){ //This is the line where it points the error
        echo 'Sucess';
    }else{
        echo 'Something';
    }
}
?>

It will access parent class properties also.

1 Comment

@Marat Badykov downvoted for my answer because I replied before him. Thats not cool bro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.