在 PHP 中不在对象上下文中时使用 $this

Using $this when not in object context in PHP

我不知道为什么会收到此错误:Fatal error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\app\index.php:19 Stack trace: #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';
    }
}
?>

半天没解决这个问题,所以我来这里

您可以使用您的实例;

<?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';
    }
}
?>

它还将访问父 class 属性。

您不在 class 的实例中,无法使用 $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';
    }
}
?>

您应该使用 $req->addReques 而不是 $this->req->addReques