As far as I thought you could either instantiate the class as so:
$class = new className();
Then to use a method in it you would just do:
$class->myMethod();
Or if you wanted to use something from within the class WITHOUT instantiating it you could do:
className::myMethod();
I'm sure I have used the latter before without any problems, but then why am I getting an error that says:
Fatal error: Using $this when not in object context
My code I am using to call it is:
// Display lists with error message
manageLists::displayLists($e->getMessage());
The class is as follows..
class manageLists {
/* Constructor */
function __construct() {
$this->db_connection = connect_to_db('main');
}
function displayLists($etext = false, $success = false) {
// Get list data from database
$lists = $this->getLists();
......
}
function getLists() {
.........
}
}
I am getting that error from this line..
$lists = $this->getLists();
When you use the format ClassName::methodName()
, you are calling the method 'statically', which means you're calling the method directly on the class definition and not on an instance of the class. Since you can't call static methods from an instance, and $this
represents the instance of the class, you get the fatal error.
// Display lists with error message
manageLists::displayLists($e->getMessage());
This is only a valid method of calling instance methods if called from within another instance method of the class. Otherwise, the call to displayLists
will be static and there will be no $this
reference. If you have a high enough error reporting, you should see a warning telling you you're calling an instance method statically.
If you are calling a method statically, $this
does not exist. Instead of:
$lists = $this->getLists();
You can do:
$lists = self::getLists();
More info on self
can be found here: When to use self over $this?
精彩评论