barraclm 0 Posted February 18 Share Posted February 18 My script has 3 classes (that are relevant to this discussion): DB, User and Validate. They are all in independent files and loaded automatically, when required, by an autoloader. Both the User class and the Validate class have a private variable $_db which is instantiated by their class constructor: $this->_db = DB::getInstance(); At the top of the script I declare new instances: $user = new User(); and $validate = new Validate(); I then call a method in $user: $found = $user->findInUsers ( .... ) From within the findInUsers method I then want to call the query method in the DB class. My problem is that I can't find a way to do this that works. I have tried $this->_db->query( ... ), $_db->query( ... ), but neither works. The error messages I am getting are: An error occurred in script '/srv/http/classes/User.php' on line 42: Undefined variable $_db Uncaught Error: Call to a member function query() on null in /srv/http/classes/User.php:42 Any pointers as to what I am doing wrong, or what I should be doing, would be most welcome. Quote Link to post Share on other sites
requinix 977 Posted February 18 Share Posted February 18 Would be a lot easier if we could see the code for User.php. Please post it by using the Code <> button in the editor. Quote Link to post Share on other sites
mac_gyver 490 Posted February 18 Share Posted February 18 1 hour ago, barraclm said: I have tried $this->_db->query( ... ) $this (programming pun intended) is the correct syntax, but produced a different error than the one you posted about the undefined variable. what was the error message in $this case? i'm going to guess that the database connection probably failed and there's no useful error handling in the code. 1 hour ago, barraclm said: $this->_db = DB::getInstance(); while not the cause of the most immediate problem, your main code should be responsible for creating the database connection, then use dependency injection to supply that to any class that needs it. by making each class responsible for getting a specific database connection, your code is not general purpose. if the data source changes, to use an additional/different database type or using a remote api, you would need to go through and edit all the current code. 2 Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.