在PHP中不在对象上下文中使用$this
我不知道为什么会出现这样的错误:在PHP中不在对象上下文中使用$this,php,fatal-error,Php,Fatal Error,我不知道为什么会出现这样的错误:Fatal error:Uncaught error:C:\xampp\htdocs\app\index.php:19堆栈跟踪:#0{main} 这是我的index.php,其中错误指出: <?php require_once 'models/Request.php'; $req = new Request; if(isset($_POST['submit'])){ $data = [ 'reqBy' => $_POST
Fatal error:Uncaught error:C:\xampp\htdocs\app\index.php:19堆栈跟踪:#0{main}
这是我的index.php
,其中错误指出:
<?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';
}
}
?>
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';
}
}
?>
我半天没能解决这个问题,所以我在这里伸出手来你可以用你的例子
它还将访问父类属性。您不在类的实例中,无法使用$this。试试这个,它会有用的
require_once'models/Request.php';
$req=新请求;
如果(isset($_POST['submit'])){
$data=[
'reqBy'=>$\u POST['reqBy'],
'off'=>$\u POST['off'],
'prob'=>$\u POST['prob']
];
回声“;
打印(数据);
回声“;
如果($req->addRequest($data)){//这是它指向错误的行
呼应“成功”;
}否则{
呼应‘某物’;
}
}
?>
你应该使用$req->addReques
而不是$this->req->addReques
@Marat Badykov对我的回答投了反对票,因为我在他之前回答了。这可不酷,兄弟。你只能在课堂上使用$this<当从对象上下文中调用方法时,伪变量$this可用$这是对调用对象的引用(通常是该方法所属的对象,但如果从辅助对象的上下文静态调用该方法,则可能是另一个对象)。
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';
}
}
?>