Jump to content

How to call a pre-existing object from within a class


Naez

Recommended Posts

[code=php:0]class dbconn
{
// SNIP
// just basic DB stuff
}

$db = new dbconn("localhost","lala","****","db");

// when the function is in comments, it works!"
/*function getsomething()
{*/
	$query = "SELECT * FROM testtable";
	$result = $db->query($query); // excute query with $result as a handle
	$numrows = $db->num_rows($result); // Get the number of rows returned or affected

	while($row = $db->fetch_array($result))
	{
		echo $row['ID'] . ' - ' . $row['information'] . '<br>';
	} // echo some data in a loop

	echo $numrows . 'rows Returned from ' . $query . '<br>';

	echo $db->return_query_num() . " Queries";
/*	}

getsomething();
*/

[/code]

 

 

Basically I can't use the following as a function (or eventually a class).  In my project I maintain an open database connection the entire time, and it works fine until I try to use the $db-> within a function or other class, then stuff gets screwed up and says this:

 

Fatal error: Call to a member function query() on a non-object in / on line W/E

Link to comment
Share on other sites

In PHP there are three scopes: global scope, class/object scope and function scope. The variable $db you define is in the global scope so you can only access it there, you can cheat and use the global keyword inside a function to bring it into the function scope, but you should not do that. Normally you cannot access things from a different scope that you are in (except for the class scope depending on the property's visibility (public, protected or private)). There are a few so-called superglobals which can be accessed from anywhere, an example could be $_GET and $_POST. To access things from the global scope within the function scope (and vice-versa) you'll have to find a way to bring the variable in there, that could be passing it as an argument.

 

Also see: http://en.wikipedia.org/wiki/Scope_(programming) and http://php.net/variables.scope

 

Could you show me a quick example of how to accomplish that?

 

function getsomething($db) { /* ... */ }

getsomething($db);

Link to comment
Share on other sites

Thanks, that really helped alot.

 

Do I have to call the database in the opening of every "function($db)" like that within the class that uses it?

 

Or should I add

 

$this->db = $db;

 

to my constructor, and then later call functions like

 

$this->db->query($query);

 

?

Link to comment
Share on other sites

If you're going to use the $db object a lot inside a class then it would perhaps be a good idea to store a reference in a property like you said. You could then pass it to the constructor and set it there. If you're just going to use it in one specific method then just pass it to that method.

Link to comment
Share on other sites

Might be worth considering turning your "db" class into a singleton. Which can then be called from anywhere.


function myfunc(){
  $db = Database::instance(); // singleton initialisation.
  $db->query("blah blah blah");
  ...// etc
}

Link to comment
Share on other sites

Also bear in mind that you might choose to rename that variable in the future, from $db to $database, meaning ANY places where you have used $db would need to be changed. Also, because $db is being used globally there is the possibility that it can be overwritten with ANY variable type in the future, causing failure in other parts of your application.

Link to comment
Share on other sites

  • 3 months later...

That's a bad idea. You'll eventually run into problems are you are coupling your things too tight and making all the things dependent on each other.

 

I was going to post a new topic about this but figured I would use this one to reduce the noise.

 

If you reference your db object or create a db object inside of a class you are working on, doesn't that tie that class to your db class? That's the trouble I'm running into with the framework/library I'm writing.

 

I want objects to be able to interact with the database but not directly or in a means that that the my db class is required for the object to work. I remember someone mentioning using a data mapping class but I can't find that thread. Can someone point me in the right direction?

Link to comment
Share on other sites

No.

 

In that case you use an interface.

 

http://en.wikipedia.org/wiki/Interface_%28computer_science%29

 


<?php

interface Database {
   function query($q);
}

public class MySQLDatabaseImpl implements Database {
   //must define $query;
}




class foo {
  public function doSomethingWithADatabase(Database $db) { //enforce usage of Database class
     return $db->query("select lol from mymom"); // you know $db will have a query method, and your object doesn't actually care what it does.
  }
}
?>

Link to comment
Share on other sites

Well, I was more thinking about how that foo class should be functional without relying on the db class. It's requesting and getting data from *insert data source* so if my friend wanted to drop foo into his app, he could use his db object as the data source without having to modify foo. So basically, foo is depenant on a data source but not a specific one. Is there a design pattern or a way of doing this? I want to keep objects seperate but have them work together. Like puzzle pieces.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.