繁体   English   中英

在PhP中将变量从一类传递到另一类

[英]Passing variables from one class to an other in PhP

您好,我正在尝试使用lorna jane mitchell博客中的说明构建我的第一个Restful Web服务和即时消息。

如果要求通过此网址: http:// localhost:8888 / lorna / index.php / tree / getpath?node_id = 75我将调用getpath函数传递给node_id,该函数get path如下所示:

  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();
  }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM