如何通过类';将变量值传递到另一个文件;


How to pass variable value to another file via class'

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

如果我在同一个文件中提取DB会很容易(但我想避免这种情况),这就是为什么我创建了一个单独的(用户隐藏的)文件,其中包含类,然后从主文件(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(在文件core.php中的posts_b类中处理),

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()的方法)

请帮忙,任何人,

谢谢。。。

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

不过,还是有办法解决这个问题的。您可以将返回值设置为一个数组,该数组包含您想要的所有值。例如:

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