PHP 类导入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7929723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:39:01  来源:igfitidea点击:

PHP Class Import

php

提问by Helen Neely

Here's a sample code that I'm trying to call from another page to help me with stats. I can't seem to get it to work. How do I import and call this class in another php file? stats.php

这是我试图从另一个页面调用以帮助我处理统计数据的示例代码。我似乎无法让它工作。如何在另一个 php 文件中导入和调用这个类?stats.php

<?php

include("config.php");
$link = mysql_connect($host, $username, $password);
mysql_select_db("mydb", $link);

class stats{

  function newReg(){

    $result = mysql_query("SELECT * FROM people where status ='registered' ", $link);
    $num_rows = mysql_num_rows($result);
     return $num_rows ;


function newApp(){
    $result = mysql_query("SELECT * FROM people where status = 'NEW' ", $link);
    $num_rows = mysql_num_rows($result);

    return $num_rows;
 }
?>

I want to call that class here in another file:

我想在另一个文件中调用该类:

<?php

require_once("stats.php");
   echo(stats.newReg());

 ?>

Is there something I'm missing here?

有什么我在这里想念的吗?

回答by Roman

you forgot 2 closing brackets

你忘记了 2 个右括号

<?php

include("config.php");
$link = mysql_connect($host, $username, $password);
mysql_select_db("mydb", $link);

class stats{

  function newReg(){
    global $link;
    $result = mysql_query("SELECT * FROM people where status ='registered' ", $link);
    $num_rows = mysql_num_rows($result);
     return $num_rows ;
  }

function newApp(){
    global $link;        
    $result = mysql_query("SELECT * FROM people where status = 'NEW' ", $link);
    $num_rows = mysql_num_rows($result);

    return $num_rows;
 }
}
?>

anyway, other file:

无论如何,其他文件:

include 'statsclassfile.php';
$myStats = new stats();
$mystats->newReg();

PS: naming conventions generally want that class names begin with a capital letter, eg: Stats

PS:命名约定通常希望类名以大写字母开头,例如: Stats

回答by Draiken

Make sure the paths are correct, maybe the config.php file is not on the same folder.

确保路径正确,可能 config.php 文件不在同一个文件夹中。

You can use absolute paths like this

您可以使用这样的绝对路径

require_once $_SERVER['DOCUMENT_ROOT'] . "/path_to_config/config.php";

And to call your stats class:

并调用您的统计类:

require_once PATH_TO_YOUR_CLASS . "stats.php"

Also make sure you name classes with CamelCased names.

还要确保您使用 CamelCased 名称命名类。