Home » Php » PHP Class Import

PHP Class Import

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

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?

How to&Answers:

you forgot 2 closing brackets

<?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

Answer:

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

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.