【问题标题】:How to pass variable value to another file via class'如何通过类将变量值传递给另一个文件
【发布时间】:2013-08-02 19:48:52
【问题描述】:

我有显示帖子的主(用户可见)文件,我需要设置分页。

如果我在同一个文件中获取数据库会很容易(但我想避免这种情况),这就是为什么我创建了一个单独的(用户隐藏的)文件,其中包含然后从主文件(blog. php):

BLOG.php(简体):

<?php
require 'core.php';

$posts_b = new Posts_b();
$posts_bx = $posts_b->fetchPosts_b();

foreach($posts_hx as $posts_hy){

   echo $posts_hy['title'];
}
?>

core.php(简体);

class Posts_b extends Core {
public function fetchPosts_b(){

    $this->query ("SELECT posts_id, title FROM posts"); 

//return
return $this->rows();

    }
}

这就像一个魅力,但现在我需要在查询中进行计数,这工作正常,并且给了我一个变量 $pages=5(在类 posts_b 中处理 - 在文件 core.php 中),

core.php(简化-带变量);

class Posts_b extends Core {
public function fetchPosts_b(){

    $this->query ("SELECT posts_id, title FROM posts"); 
    $pages=5;   

//return
return $this->rows();

    }
}

现在我需要一种方法来将此变量值返回到 blog.php(我返回 rows() 的方式)

请帮助,任何人,

谢谢...

【问题讨论】:

  • 所以问题是,如何将变量 $pages 与 $this->rows() 一起传递回 blog.php ?

标签: php class include


【解决方案1】:

一个函数只能有一个返回值。

但有一些方法可以解决这个问题。你可以让你的返回值是一个包含所有你想要的值的数组。例如:

return array("pages"=>$pages, "rows"=>$this->rows());

然后在你的代码中

require 'core.php';

$posts_b = new Posts_b();
$posts_bx = $posts_b->fetchPosts_b();
$pages = $posts_bx["pages"];
foreach($posts_hx["rows"] as $posts_hy){

   echo $posts_hy['title'];
}
?>

或者您可以调整作为参考提供的输入参数

public function fetchPosts_b(&$numRows){

  $this->query ("SELECT posts_id, title FROM posts"); 

  //return
  return $this->rows();

}

在您的代码中

require 'core.php';

$posts_b = new Posts_b();
$pages = 0;
$posts_bx = $posts_b->fetchPosts_b(&$pages);

foreach($posts_hx["rows"] as $posts_hy){

   echo $posts_hy['title'];
}
?>

或者您可以选择在 fetchPosts_b 方法之外找出您的分页。

$posts_bx = $posts_b->fetchPosts_b();
$pages = floor(count($posts_bx)/50);

【讨论】:

  • 尝试了第一个解决方案,它就像一个魅力。非常感谢你。 p.s.我写错了(写问题时)insted posts_hx 它是 bx (但一般的 ide 是一样的)...
猜你喜欢
  • 2019-05-02
  • 2015-05-22
  • 1970-01-01
  • 2019-02-01
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 2021-01-21
相关资源
最近更新 更多