【问题标题】:Slim PHP : Fatal error: Using $this when not in object contextSlim PHP:致命错误:不在对象上下文中使用 $this
【发布时间】:2015-07-12 13:00:06
【问题描述】:

我正在使用超薄微框架开发一个 php 应用程序

那是我的 index.php 文件:

<?php

require 'Slim/Slim.php';
include 'db.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get("/", function () {
    echo "<h1>HELLO USER</h1>";
});

    //Registration view

    $app->post("/reg", function (){

        $request = $this->app->request();
        $username = $request->post('username');
        $password = $request->post('password');        
        $name = $request->post('name');
        $email = $request->post('email');
        try { 
            $sql = "INSERT INTO users (username, hash, name, email) VALUES (:username, :password, :name, :email)";
            $s = $this->dbh->prepare($sql);
            $s->bindParam("username", $username);
            $s->bindParam("hash", $password);            
            $s->bindParam("name", $name);
            $s->bindParam("email", $email);
            $s->execute();
        } catch(\PDOException $e) {
            echo 'Exception: ' . $e->getMessage();
        }

    }); // Login Function End



$app->get('/updates', function () {
    //Display users

});


// run the Slim app

$app->run();

?>

我有 index.html 文件,其中包含像这样的 ajax 跨域请求:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>INDEX</title>
<link href='css/style.css' rel='stylesheet' type='text/css'/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>


$(document).ready(function(){
    $("#put").submit(function(event) {
        event.preventDefault();
        $.ajax({
            url: 'http://localhost/slim/reg',
            type: 'POST',
            crossDomain: true,
            data: $("#put").serializeArray(),
            success: function(data) {console.log(data); }
        }); 
    });
});



</script>

</head>

<body>

<form id="put">
    Registration <br/>
    username: <input type="text" name="username" id="username"/><br />
    password: <input type="password" name="hash" /><br />
    name: <input type="text" name="name" /><br />
    email: <input type="text" name="email" /><br />
    <input type="submit" />
</form>


</body>
</html>

问题是当我尝试在我的 index.html 文件中提交表单时,我总是得到:

致命错误:在第 19 行的 C:\wamp\www\slim\index.php 的对象上下文中使用 $this

【问题讨论】:

  • 你试过删除$this-&gt;?
  • 我将第 19 行设为这样: $request = $app->request();我在控制台中遇到错误:500 Internal server error

标签: php ajax cross-domain slim


【解决方案1】:
$request = $this->app->request();

这很可能是第 19 行,它不在实例方法内,甚至不在类定义内。因此,没有实例引用,因此没有 $this。
你期望 $this 是什么?显然你需要一个app 和一个dbh。是什么提供了这些属性/实例?
app 可能是 $app = new \Slim\Slim();。但是dbh 应该是什么? (一个数据库句柄,好的,但是是什么提供了这个数据库连接句柄?)

【讨论】:

    【解决方案2】:

    基本上问题是@VolkerK 提到的。

    如果您希望您的闭包方法了解在您的方法范围之外定义的变量,您需要使用use 关键字。

    $app->post("/reg", function () use ($app) {
        $request = $app->request();
    }
    

    【讨论】:

      【解决方案3】:

      解决方案: 完整的工作 index.php 现在看起来像:

      <?php
      
      
      require 'Slim/Slim.php';
      include 'db.php';   
      
      \Slim\Slim::registerAutoloader();
      
      $app = new \Slim\Slim();
      $app->contentType('application/json');
      
      $app->get('/', 'home');
      $app->post('/adduser', 'addUser');
      $app->get('/users', 'getUsers');
      
      // Home view
      
      function home() {echo "Welcome to the platform !";}
      
      // Add users
      function addUser() {
        global $app;
        $req = $app->request();
      
        $sql = "INSERT INTO users (username, password, fullname, email) VALUES (:username, :password, :fullname, :email)";
        try {
          $db = getDB();
          $stmt = $db->prepare($sql);
            $stmt->bindParam("username", $_POST['username']);
            $password = md5($_POST['password']);
            $stmt->bindParam("password", $password);
            $stmt->bindParam("fullname", $_POST['fullname']);
            $stmt->bindParam("email", $_POST['email']);
            $stmt->execute();
            $db = null;
        } catch(PDOException $e) {
            echo "Connection Error";
        }
      }
      
      // Get Users
      
      function getUsers() {
          $sql = "SELECT username,fullname,email FROM users ORDER BY id";
          try {
              $db = getDB();
              $stmt = $db->query($sql);  
              $users = $stmt->fetchAll(PDO::FETCH_OBJ);
              $db = null;
              echo '{"users": ' . json_encode($users) . '}';
          } catch(PDOException $e) {
              //error_log($e->getMessage(), 3, '/var/tmp/php.log');
              echo '{"error":{"text":'. $e->getMessage() .'}}'; 
          }
      }
      
      // run the Slim app
      
      $app->run();
      
      ?>
      

      【讨论】:

      • 我真的会尽量避免使用global
      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      相关资源
      最近更新 更多