Jump to content

Problem with calling a method from within a method in another class


Recommended Posts

 

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.

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.

  • Like 2
  • 3 weeks later...
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.