Referencing classes as className::methodName() - php

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?

Related

PHP Fatal error: Uncaught Error: Using $this when not in object context [duplicate]

I've got a problem:
I'm writing a new WebApp without a Framework.
In my index.php I'm using: require_once('load.php');
And in load.php I'm using require_once('class.php'); to load my class.php.
In my class.php I've got this error:
Fatal error: Using $this when not in object context in class.php on line ... (in this example it would be 11)
An example how my class.php is written:
class foobar {
public $foo;
public function __construct() {
global $foo;
$this->foo = $foo;
}
public function foobarfunc() {
return $this->foo();
}
public function foo() {
return $this->foo;
}
}
In my index.php I'm loading maybe foobarfunc() like this:
foobar::foobarfunc();
but can also be
$foobar = new foobar;
$foobar->foobarfunc();
Why is the error coming?
In my index.php I'm loading maybe
foobarfunc() like this:
foobar::foobarfunc(); // Wrong, it is not static method
but can also be
$foobar = new foobar; // correct
$foobar->foobarfunc();
You can not invoke the method this way because it is not a static method.
foobar::foobarfunc();
You should instead use:
$foobar->foobarfunc();
If however, you have created a static method something like:
static $foo; // your top variable set as static
public static function foobarfunc() {
return self::$foo;
}
then you can use this:
foobar::foobarfunc();
You are calling a non-static method :
public function foobarfunc() {
return $this->foo();
}
Using a static-call :
foobar::foobarfunc();
When using a static-call, the function will be called (even if not declared as static), but, as there is no instance of an object, there is no $this.
So :
You should not use static calls for non-static methods
Your static methods (or statically-called methods) can't use $this, which normally points to the current instance of the class, as there is no class instance when you're using static-calls.
Here, the methods of your class are using the current instance of the class, as they need to access the $foo property of the class.
This means your methods need an instance of the class -- which means they cannot be static.
This means you shouldn't use static calls : you should instanciate the class, and use the object to call the methods, like you did in your last portion of code :
$foobar = new foobar();
$foobar->foobarfunc();
For more informations, don't hesitate to read, in the PHP manual :
The Classes and Objects section
And the Static Keyword page.
Also note that you probably don't need this line in your __construct method :
global $foo;
Using the global keyword will make the $foo variable, declared outside of all functions and classes, visibile from inside that method... And you probably don't have such a $foo variable.
To access the $foo class-property, you only need to use $this->foo, like you did.
If you are invoking foobarfunc with resolution scope operator (::), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this when not in object context. $this does not exist in class context.
If you enable E_STRICT, PHP will raise a Notice about this:
Strict Standards:
Non-static method foobar::foobarfunc() should not be called statically
Do this instead
$fb = new foobar;
echo $fb->foobarfunc();
On a sidenote, I suggest not to use global inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.
First you understand one thing, $this inside a class denotes the current object.
That is which is you are created out side of the class to call class function or variable.
So when you are calling your class function like foobar::foobarfunc(), object is not created.
But inside that function you written return $this->foo(). Now here $this is nothing. Thats why its saying Using $this when not in object context in class.php
Solutions:
Create a object and call foobarfunc().
Call foo() using class name inside the foobarfunc().
When you call the function in a static context, $this simply doesn't exist.
You would have to use this::xyz() instead.
To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I’m static or an object?
Fast method : (new foobar())->foobarfunc();
You need to load your class replace :
foobar::foobarfunc();
by :
(new foobar())->foobarfunc();
or :
$Foobar = new foobar();
$Foobar->foobarfunc();
Or make static function to use foobar::.
class foobar {
//...
static function foobarfunc() {
return $this->foo();
}
}
It seems to me to be a bug in PHP.
The error
'Fatal error: Uncaught Error: Using $this when not in object context
in'
appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:
Class_Name
{
function foo()
{
$this->do_something(); // The error appears there.
}
function do_something()
{
///
}
}
While the error is here:
Class_Name::foo();
$foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();
Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.
Just use the Class method using this foobar->foobarfunc();

PHP7: Static class function can't be called/seen until class is instanced

I have a custom class called Error that I autoload before anything else. In my custom class, I have a constructor and a singleton Get function like this:
class Error
{
// Singleton object. Leave $me alone.
private static $me;
public $errors; // Array of errors
public $style; // CSS rules to apply to error elements
private function __construct($style = "border:1px solid red;")
{
$this->errors = array();
$this->style = $style;
}
// Get Singleton object
public static function getError()
{
if(is_null(self::$me))
self::$me = new Error();
return self::$me;
}
//...
}
In my master include, I've always prepared a singleton of this custom class before the core logic:
$Error = Error::getError();
However, in PHP 7 this is now giving me an error:
Fatal error: Uncaught Error: Call to undefined method
Error::getError()
Can you help me understand why this doesn't work anymore? I've tried this instead to check whether the Error class is being loaded at all, and it does work (and call the constructor):
$Error = new Error();
Somehow I can't call the static class function unless I've instanced this class. This will break a lot of other logic I have if that's truly a change in php7.
As of PHP 7, PHP includes a built-in Error class which appears to be in conflict with your application's Error class.
PHP pre-defined Error class
If your own application's class is not defined within a custom namespace and you are attempting to call Error::getError(), PHP will assume you mean the built-in class which has no defined getError() method. (It does have a similar getMessage() non-static method).
You may work around this by adding a custom namespace to your application, which is a recommended practice anyway. Or if your application has no requirement to continue running under PHP 5.x, consider refactoring it to use the built-in Error class functionality instead.

Fatal error: Using $this when not in object context in pdo [duplicate]

I've got a problem:
I'm writing a new WebApp without a Framework.
In my index.php I'm using: require_once('load.php');
And in load.php I'm using require_once('class.php'); to load my class.php.
In my class.php I've got this error:
Fatal error: Using $this when not in object context in class.php on line ... (in this example it would be 11)
An example how my class.php is written:
class foobar {
public $foo;
public function __construct() {
global $foo;
$this->foo = $foo;
}
public function foobarfunc() {
return $this->foo();
}
public function foo() {
return $this->foo;
}
}
In my index.php I'm loading maybe foobarfunc() like this:
foobar::foobarfunc();
but can also be
$foobar = new foobar;
$foobar->foobarfunc();
Why is the error coming?
In my index.php I'm loading maybe
foobarfunc() like this:
foobar::foobarfunc(); // Wrong, it is not static method
but can also be
$foobar = new foobar; // correct
$foobar->foobarfunc();
You can not invoke the method this way because it is not a static method.
foobar::foobarfunc();
You should instead use:
$foobar->foobarfunc();
If however, you have created a static method something like:
static $foo; // your top variable set as static
public static function foobarfunc() {
return self::$foo;
}
then you can use this:
foobar::foobarfunc();
You are calling a non-static method :
public function foobarfunc() {
return $this->foo();
}
Using a static-call :
foobar::foobarfunc();
When using a static-call, the function will be called (even if not declared as static), but, as there is no instance of an object, there is no $this.
So :
You should not use static calls for non-static methods
Your static methods (or statically-called methods) can't use $this, which normally points to the current instance of the class, as there is no class instance when you're using static-calls.
Here, the methods of your class are using the current instance of the class, as they need to access the $foo property of the class.
This means your methods need an instance of the class -- which means they cannot be static.
This means you shouldn't use static calls : you should instanciate the class, and use the object to call the methods, like you did in your last portion of code :
$foobar = new foobar();
$foobar->foobarfunc();
For more informations, don't hesitate to read, in the PHP manual :
The Classes and Objects section
And the Static Keyword page.
Also note that you probably don't need this line in your __construct method :
global $foo;
Using the global keyword will make the $foo variable, declared outside of all functions and classes, visibile from inside that method... And you probably don't have such a $foo variable.
To access the $foo class-property, you only need to use $this->foo, like you did.
If you are invoking foobarfunc with resolution scope operator (::), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this when not in object context. $this does not exist in class context.
If you enable E_STRICT, PHP will raise a Notice about this:
Strict Standards:
Non-static method foobar::foobarfunc() should not be called statically
Do this instead
$fb = new foobar;
echo $fb->foobarfunc();
On a sidenote, I suggest not to use global inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.
First you understand one thing, $this inside a class denotes the current object.
That is which is you are created out side of the class to call class function or variable.
So when you are calling your class function like foobar::foobarfunc(), object is not created.
But inside that function you written return $this->foo(). Now here $this is nothing. Thats why its saying Using $this when not in object context in class.php
Solutions:
Create a object and call foobarfunc().
Call foo() using class name inside the foobarfunc().
When you call the function in a static context, $this simply doesn't exist.
You would have to use this::xyz() instead.
To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I’m static or an object?
Fast method : (new foobar())->foobarfunc();
You need to load your class replace :
foobar::foobarfunc();
by :
(new foobar())->foobarfunc();
or :
$Foobar = new foobar();
$Foobar->foobarfunc();
Or make static function to use foobar::.
class foobar {
//...
static function foobarfunc() {
return $this->foo();
}
}
It seems to me to be a bug in PHP.
The error
'Fatal error: Uncaught Error: Using $this when not in object context
in'
appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:
Class_Name
{
function foo()
{
$this->do_something(); // The error appears there.
}
function do_something()
{
///
}
}
While the error is here:
Class_Name::foo();
$foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();
Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.
Just use the Class method using this foobar->foobarfunc();

Non-static method tNG_log::log() should not be called statically, assuming $this from incompatible context

I am getting the above error - here is the code that it is referring to:
function executeTransaction() {
tNG_log::log('tNG' . $this->transactionType, 'executeTransaction', 'begin');
if ($this->started) {
tNG_log::log('tNG' . $this->transactionType, 'executeTransaction', 'end');
return false;
}
I am unsure how to edit the above code effectively to make the error message go away. I am aware that I can edit the php.ini file so that these errors do not show, however I would rather fix the code
The method log() of the class tNG_log() is not defined as a static function.
Static methods can be called without creating an object from the class, like in your example, class::staticFunction().
This only works when in the class, the code is something like:
class tNG_log {
public static function log(...) {
// ...
}
}
Assuming the tNG_log-code is correct and should not be called staticly, the solution is to create an object from the class:
$tnglog = new tNG_log();
$tnglog->log(...);
If you want more information, please start with reading http://php.net/manual/en/language.oop5.static.php

PHP Error: Using $this when not in object context

I keep getting this error PHP Fatal error: Using $this when not in object context and I cannot for the life of me figure out why. Is there another set of eyes that can help? I have another class set up similarly and that one isn't throwing errors. code is as follows (skimmed down for easier reading):
include '< const class id >.php';
class ParseFunctions {
private $_id = '';
public function __construct(){
$id = new IDS;
$this->_id = $id::<const class id>;
}
public function set_id(){
$new_id = $this->id; <--- this line throws the error
$print_r($new_id);
}
}
any help is appreciated! thank you!
It's because you are calling the set_id method statically (along the lines of ParseFunctions::set_id()).
You can't use $this in that (static) context. You can only use $this within an instance (object context), i.e., $obj = new ParseFunctions; $obj->set_id(); (no context error will be thrown when the pertinent line is reached)
Though you haven't shown how you call set_id() in your code. The likely error is that you are calling it in a static context somewhere like this:
ParseFunctions::set_id()
The is static context and would disallow use of $this within the called method since their is no concrete object that has been instantiated.

Categories