Codeigniter RESTful API Server

2019-07-16 10:23发布

问题:

I'm trying to create the RESTful API server in Codeigniter. So far, i followed the instructions i got from here https://github.com/philsturgeon/codeigniter-restserver. So far so good, I created a simple controller to test, so i build a hello.php:

<?php 

include(APPPATH.'libraries/REST_Controller.php');

class Hello extends REST_Controller {
  function world_get() {
    $data->name = "TESTNAME";
    $this->response($data); 
  }
}

?>

When I try to run it by entering http://localhost/peojects/ci/index.php/hello/world I get the error:

<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">

<h4>A PHP Error was encountered</h4>

<p>Severity: Warning</p>
<p>Message:  Creating default object from empty value</p>
<p>Filename: controllers/hello.php</p>
<p>Line Number: 7</p>

</div>{"name":"TESTNAME"}

What is the issue here?

回答1:

$data has not previously been set/defined. You would need to do something like: $data = new StdObject; and then assign properties to it: $data -> name = "TESTNAME";

class Hello extends REST_Controller {
  function world_get() {
    $data = new StdObject;
    $data->name = "TESTNAME";
    $this->response($data); 
  }
}

Or according to the example, you might use an array instead:

class Hello extends REST_Controller {
  function world_get() {
    $data = array();
    $data['name'] = "TESTNAME";
    $this->response($data); 
  }
}