This question already has answers here:
Call to a member function on a non-object
(4 answers)
Closed 10 years ago.
I have recently started coding in php again and am learning Object Orientated PHP.
I have come across an issue that I cannot seem to get my head round with an error:
Fatal error: Call to a member function verify_Username_And_Password() on a non-object in C:\wamp\www\sso\lib\UserManagement.php on line 57
I understand that the program seems to think that the mysql class variable is empty but not why when it is instanced.
The function verify_Username_And_Password ($username, $password) is defined in the class Mysql.
The following is code from UserManagement.php with parts taken out that are not needed.
<?PHP
require_once 'lib/Mysql.php';
class UserManagement {
private $mysql;
function __construct(){
session_start();
$this->manage_Session();
$this->mysql = new Mysql();
}
function validate_User ($username, $password){
$user_Check = $this->mysql->verify_Username_And_Password($username, md5($password));
if($user_Check) {
return true;
} else {
return false;
}
}
}
I must be missing something basic about OO in PHP. I would be grateful for any advice anyone can give. I will be happy to post more code if needed.
As requested here is:
Mysql.php pastebin.
UserManagement.php pastebin
Without seeing the code that does the work, my guess would be you are using the validate_User method without first constructing a UserMangement object.
$um = new UserManagement();
$um->validate_User($username, $password);
If you wish to call validate_User without first constructing a UserManagement object it needs to be a static method. Without the UserManagement object being constructed Mysql is never constructed and saved in the attribute inside your class.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i have a class called Users.php .Inside of this class i create a local variable like this:
class Users
{
public $dbHelper;
}
inside of the Users class is a function called init inside of this function i set the $dbHelper variable to be a object of the DatabaseHelper.php class i wrote:
public function init()
{
$this->dbHelper = new DatabaseHelper();
}
now i try to call a method inside of the DatabaseHelper class like this:
public function login()
{
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
But currently its giving me this error:
Call to a member function executeSQLCommandWR() on null.
Why is the dbHelper variable null? In other oop programming langauages this works why not in this case?
Thanks for any help
Edit:
Im sorry i couldnt post all the code for this question because i was kind of in a rush when i created this question.
I call the init method as soon as my page gets loaded. It really seems like a scope problem i will try some of the answers and try to solve this problem. Thanks for everyone trying to help
I think you do not called the init, but init is not a good practice if you call it right after the instantiate. You can put it into the constructor, but that wont be a clean code too.
Instead of this use:
public function login() {
if (empty($this->dbHelper)) {
$this->dbHelper = new DatabaseHelper();
}
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
or
public function login() {
$this->init();
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
public function init() {
if (empty($this->dbHelper)) {
$this->dbHelper = new DatabaseHelper();
}
}
Second is better because of single responsible principle IMHO.
Notice that you have not initialized the member variable $dbHelper,
you haven't provided it with any value, therefore, it's null.
public function login()
{
$this->init();
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
It seems to be a variable scope problem call the function init in the login function to define the variable
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 6 years ago.
I am new in php, and wonder why I getting this, need expert to guide. Thanks.
PHP Fatal error: Call to a member function rowCount() on resource in C:\inetpub\wwwroot\xxx\xxx.php on line 9
<?php
include 'connect_db.php';
$conn = null;
$sqlGetFeedback = "Select * from t_abc";
$resFB = $conn->query($sqlGetFeedback);
$rows = array();
if($resFB->rowCount()){
echo json_encode($resFB->fetchAll(PDO::FETCH_ASSOC));
} else {
echo '[{}]';
}
?>
$conn is an object reference that you have set to null which essentially means "no object there". And then you call the method query that operates on an object, which you don't have because it is null.
In your included file connect_db.php maybe there is a constructor for the object that implements the method query or there is a factory function that returns a constructed object that implements query.
I hope you know some basics about object oriented programming, or else all this perhaps won't help you much. In this case grab a book learn about this programming paradigm first.
Your connection is referencing the $conn = null.
Soln:
It's either you place the include connect_db.php after the $conn
Or
Remove the $conn = null entirely.
You should have $conn in your connect_db.php
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 9 years ago.
I'm working with a few different classes across different php files. For some reason, the first time I call my function, it works correctly, but the second call results in an error.
This is my "something" class (edited for public view)
class something{
private $db;
function myfunction($sql){
$db = new db();
$results = $db->select("sql query using $sql");
return(empty($results[0]['name'])?0:1);
}
}
"db" is another class I'm using to handle the database queries etc. I don't believe the issue lies in this file since the first call works correctly.
Here's the code I'm using to test it. This is in a different php file from the "something" class.
$something = new something();
echo($something->myfunction('string'));
echo($something->myfunction('string2'));
As I mentioned, the first call ("string") works correctly, but the second one ("string2") fails. This is the error I get.
Call to a member function select() on a non-object
I don't believe it's an issue with the select function (or the db class) since the first call works correctly. I think the issue lies with me declaring $db in "myfunction", but I'm not sure why.
First off, I would shy away from creating a new $db every time you call that function unless you're going to explicity destroy it at the end of the function call.
Secondly, you are creating the class variable private $db but you aren't assigning the db object to it.
You should try the following:
class something{
private $db;
function myfunction($sql){
if(!isset($this->db)){
$this->db = new db();
}
$results = $db->select("sql query using $sql");
return(empty($results[0]['name'])?0:1);
}
}
I feel like that should work better. Let me know!
Edit:
Right- so either do it as my code above shows, or use the class constructor to do it. In PHP the constructor object isn't the class name, it is defined as __construct()
My approach would be either to extend the DB class as I mentioned in my comment above, or to do it in the constructor. My reasoning behind that is because I just don't like creating class-instances inside of methods if I can avoid it, I'd rather make it once when the object is created. SOoooooOOOoOOoOOo:
class something{
private $db;
public function __construct(){
$this->db = new db();
}
function myfunction($sql){
$results = $this->db->select("sql query using $sql");
return(empty($results[0]['name'])?0:1);
}
}
Notice the usage of $this->
That's a PHP thing. Get familiar with it if you aren't- you'll be using it a BUNCH. :)
Good luck!
What kind of DB wrapper are you using? Is database persistence turned on? It migth be disconnecting and not reconnecting the second time round, thus returning an empty DB object.
Can I assume that this is a short version of your code, and you have some logic to instantiate $db only once? In that case you must change that line from
$db = new db();
to
$this->db = new db();
Otherwise db object will be gone at the end of the call.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fatal error: Call to a member function query() on a non-object in
I have a class file, lets call it 'stuff'
Stuff.class
inside there is a class
class Stuff {
and in there I have a public static function
public static function morestuff() {
}
Inside I need to call another function for a query
$q="Select from contacts where id =". $this->$db->escapeVal($ID)".";
But I get errors.
$q="Select from contacts where id =". escapeVal($ID)".";
Returns
Call to undefined function escapeVal()
$q="Select from contacts where id =". $db->escapeVal($ID)".";
Returns
Call to a member function escapeVal() on a non-object
$q="Select from contacts where id =". $this->$db->escapeVal($ID)".";
Returns
Using $this when not in object context
So what do I put?
EDIT:
A similar function in the same file has the following code
'id' = '" . $this->db->escapeVal($this->_Id) . "'
However when I try to use this code in my mysql query I get the following error
Using $this when not in object context
I suspect that $db is a global variable, so try
public static function morestuff() {
global $db;
$q="Select from contacts where id =". $db->escapeVal($ID);
}
If the function is in the same class and is also static you will call it like
self::escapeVal($ID);
You are not understanding the concept of OOP. $this is a variable which refers to the current object (or this object). Meaning:
class Test {
public function __construct() { //Called when object is instantiated
var_dump($this);
}
}
$test = new Test();
You'll get something similar to
object(Test)#1 (0) { }
You cannot use $this outside of a class method. It just doesn't work that way.
About the error you're having, try to figure out where is the database connection stored. That connection should either be passed to the object for storing as a field, or directly to the method to work with it internally.
Programming isn't about copy/pasting code that works.
Because your function is static, the variable $this won't exist inside it.
To solve your problem, there are 2 solutions:
Make $db a static variable, meaning it will be the same in every instance.
Remove the static keyword from the function morestuff(). In this case you will need to make an instance of the class in order to make a call to morestuff().
$Stuff->db->escapeVal($id)
started to work. So happy i got it to work, Thank you very one.
This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 9 years ago.
I am getting a Fatal error: Using $this when not in object context in Stemmer.php on line 317.
At the moment I am using the Stemmer class which I found on the internet to change words to their stemmed version before searching the database for matches.
I have read all the related posts where people are having a similar problem. The difference is that the code causing the error definitely is within object context (the code below will show that). The other strange thing is that there are parts of the code very similar to the error before and after it which don't seem to cause any difficulties. At different times the error line has changed to some of these other lines.
Does anyone have any ideas what could be causing the problem. I am using php5.1.34 if this makes any difference.
Code which calls the Stemmer class
if (isset($search) && $search != "") {
$filtered_words = WordFilter::filter($search);
foreach($filtered_words as $word) {
if(strlen($word) <= 2) {
continue;
}
$w = Stemmer::stem($word);
$stemmed_words[] = $w;
}
}
Stemmer class:
class Stemmer
{
...
if ( strlen($word) > 2 ) {
**$word = $this->_step_1($word);**
}
...
}
Even when the error occurs in difference places within the code it always seems to be when there is code trying to call another method within the same class. Could this be a bug in php5 that I am not aware of? Any advice would be most appreciated.
Thanks
Archie
Your using $this in a static method.
Static methods don't have an instance; you have to access other static properties/methods or create an instance within the static method to work with.
E.g.
Stemmer::_step_1($word);
where declared in class as
public static function _step_1($var) { [...] }
This error ocurred, because stem is not a static class, he uses $this. Try to use this code:
$Stemmer = new Stemmer;
$Stemmer->stem($word);