Jump to content

Not including correctly


dannon

Recommended Posts

Hi,

I have a class:

class Toplist {
    public function get_article($id) {
        $id = (int) $id;
        
        $articles = array();
        
        $query = $db->sql_query("SELECT * FROM `toplist` WHERE `id` = '$id'");
        $result = $db->sql_fetchrowset($query);

        return $articles;
    }
}

 

and I get

Notice: Undefined variable: db in classToplist.php on line 11

 

Fatal error: Call to a member function sql_query() on a non-object in classToplist.php on line 11

 

the variable db is in ./models/config.php and it isn't working on the classToplist.

I have a feeling that this happens because the config file is not a class.

 

How can I fix this?

Link to comment
https://forums.phpfreaks.com/topic/258007-not-including-correctly/
Share on other sites

Try

 

require('./models/config.php');

 

above your function in your class.  You may also want to throw in an empty constructor for your class.

 

Nope. ;(

I have tried require before.

Above the function gives me

Parse error: syntax error, unexpected T_REQUIRE_ONCE, expecting T_FUNCTION in C:\xampp\htdocs\retrite\rt_kernel\classToplist.php on line 7

and it isn't working inside of the function.

Oh. Duh. I should have read your intro more carefully. Yes, this is happening because the config file is not a class. You only use $object->variable or $object->function when dealing with objects of classes. You may have to re-write some code to either make a class out of your config stuff, or so your db doesn't rely on a class.

You get those errors because $db does not exist inside of the class. A variable ($db, in this case) that is defined outside of a function (or method) is not available inside the function or method. There are a couple of solutions to this, the most commonly recommended, is to add the variable to the function (method) parameter list:

 

class Toplist {
  public function get_article($db, $id) {
  // ...
  }
}

# Then pass it in the call

$ToplistObj->get_article($db, $id);

 

However, there may be a different/better solution depending on a couple of things:

1) Is this your entire class? or are there other methods, particularly ones that will need $db?

2) Does this class extend some other class?

 

 

Whether or not config.php defines a class is not really material to the first error message. However, once you fix the scope issue (above), the type of the $db variable may come into question.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.