Forum Moderators: coopster

Message Too Old, No Replies

OOP PHP Classes

how to reference one class from another

         

eaden

7:59 am on Apr 17, 2003 (gmt 0)

10+ Year Member



I am using a db class which I use like so :

$db = new db;
$results = $db->fetch_results("select * from table");

etc.

I want to make a class called records.

<?
class Records {

function latestRecords() {
return $db->get_results("select * from records order by id desc limit 0,10");
} // End latestRecords()
}
?>

My question is about using the $db object inside a class. I.e. the class uses $db, as well as the script outside the class using $db.

For an ordinary function I use "global $db" which works fine, but what's the best way to do this for a class?

Nick_W

8:05 am on Apr 17, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



>best way

Up to you ;)

You can either call the original class in the second like: $db=new db; (require() the original class first)

Or, you can use the Extends Keyword [php.net]

HTH

Nick

eaden

8:17 am on Apr 17, 2003 (gmt 0)

10+ Year Member



Thanks for the reply, but regards to your first answer, I don't want to create 2 copies of the db class, only one. And isn't require() for files? and not classes? ( all the code is in one file )

And regards to the second answer, Neither class extends the other, they are both completely seperate, except one uses the other.

I guess my question really is how do I access an Object that already exists outside the class, from inside a class.

Nick_W

8:20 am on Apr 17, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, you just need to pass it to the function you need, or the constructor of the second class. Try it...

Nick

andreasfriedrich

10:32 am on Apr 17, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Nick is right. A record object would be probably created by your DB class. When doing so pass a reference to the db instance when calling the constructor and store it in that newly created instance. Then use it in your records object just like you did before in your script.

Andreas