Using $this when not in object context in PHP
14,571
Solution 1
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';
}
}
?>
Solution 2
You should use $req->addReques
insted of $this->req->addReques
Solution 3
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.
Related videos on Youtube
Author by
thisisnotwakanda
Updated on June 11, 2022Comments
-
thisisnotwakanda almost 2 years
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
-
Admin over 5 yearsYou 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).
-
-
Ugur Kazdal over 5 years@Marat Badykov downvoted for my answer because I replied before him. Thats not cool bro.