【问题标题】:Passing variables from one class to an other in PhP在 PhP 中将变量从一个类传递到另一个类
【发布时间】:2015-11-18 09:45:05
【问题描述】:

您好,我正在尝试构建我的第一个 RESTful Web 服务,我正在使用来自 lorna jane mitchell 博客的说明。

如果请求来自这个 URL:http://localhost:8888/lorna/index.php/tree/getpath?node_id=75 我调用函数 getpath 传递 node_id 函数获取路径如下所示:

  class NestedSet
    {
       public function getPath($id) {

    $sql = "SELECT p." . $this->pk . ", p." . $this->name . " FROM ". $this->table . " n, " . $this->table . " p WHERE n.lft BETWEEN p.lft AND p.rgt AND n." . $this->pk ." = " . $id . " ORDER BY p.lft;";
       $result = $this->db->query($sql);
       if ($result->num_rows == 0) {
       return $this->error(1, true);
       }
       $path = array();
       $i = 0;
       while ($row = $result->fetch_assoc()) {
        $path[$i] = $row;
        $i++;
       }
      return $path;
     }

    } 

现在我想将此变量 $path 传递给如下所示的 JsonView 类:

    class JsonView extends ApiView {
public function render($path) {
    header('Content-Type: application/json; charset=utf8');
    echo json_encode($path);
    return true;
   }
   }





   class ApiView {
     protected function addCount($data) {
     if(!empty($data)) {
        // do nothing, this is added earlier
     } else {
        $data['meta']['count'] = 0;
       }
        return $data;

     } 
     }

关于如何通过这个 JsonView 类传递变量 $path 或任何其他变量的任何想法。 非常感谢您的宝贵时间:)

UPDATE 这是创建嵌套类对象的代码

public function getAction($request) {
  $data = $request->parameters;

  if(isset($request->url_elements[2])) {

    switch ($request->url_elements[2]) {
      case 'getpath':

      $id = $data['node_id'];

      $nested = new NestedSet();
      $nested->getPath($id);

      $api = new JsonView(); 
      $api->render($path); 

      break;

      default:
      # code...
      break;
    }
  } else {
    $nested = new NestedSet(); 
    echo $nested->treeAsHtml();
  }
}

【问题讨论】:

    标签: php web-services restful-url restful-architecture


    【解决方案1】:

    只需创建 JsonView 的对象,然后使用该对象调用函数渲染。

    $api = new JsonView;
    $api->render($path);
    

    【讨论】:

    • @akhilp255 我试过了,我得到了这个错误注意:未定义的变量:第 66 行 /Applications/MAMP/lorna/controllers/TreeController.php 中的路径
    • 更正您上面提到的错误。 $path 仅在类内可用。调用函数 getPath() 后返回路径内的值。您必须将其保存在变量中,然后传递给下一个函数。 $nested = new NestedSet(); $path = $nested->getPath($id); $api = new JsonView(); $api->render($path);
    • 是的,现在可以了 :) 非常感谢您的宝贵时间
    猜你喜欢
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多