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.
Related
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
This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 8 years ago.
I have seen registry pattern questions on here, but right now I'm being thrown off by the error message I'm receiving: Using $this when not in object context...
I took the code sample from http://avedo.net/101/the-registry-pattern-and-php/ and I have pored over these lines of code, but I just can't wrap my head around the problem.
EDIT: I get the feeling from the answers that the article I've linked to shouldn't be considered "working code"...
Here is a snippet of my registry class code:
class registry {
//Holds variables, objects, etc.
private $reg = array();
private static $instance = null;
public static function getInstance() {
if($this->instance === null) { //THROWS THE FATAL ERROR
$this->instance = new registry();
}
return $this->instance;
}
//Disallow creation of new objects, forcing use of the Singleton
private function __construct() {}
private function __clone() {}
What I'm not really understanding is WHY this is throwing that error. The way I understood $this was that it referred to whatever called the method, which is this snippet from my init.php file:
//Instantiate registry
$registry = registry::getInstance();
I'm feeling a little burned out from reading and coding (these past few days I've been dedicated to teaching myself how MVC works by building my own barebones little web framework). I must be missing something simple, but it also seems to me that this is exactly what the article illustrates. For what it's worth, I'm using PHP 5.x.
If anyone feels they need to clear up some of these concepts for me, please feel free. :) As always, thanks for taking the time to read this.
You are referencing the $this context variable, which is not available when calling a method statically.
You are using the class context (calling foo::bar()) rather than the object context ($obj->foo())
As it is a singleton you should be referencing the static property using the self:: operator.
For example:
public static function getInstance() {
if(null == self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
You can't call $this inside a static method.
http://php.net/manual/en/language.oop5.static.php
You have a static function and accessing a static var, use:
self::$instance
$this-> is used in object context, self:: is used to access static class members.
It throws an error for the exact reason that it says it does.
You are not in an object context when you call a STATIC function, therefore $this does not exist.
self::$instance will work for you instead.
I think you're getting confused between instance and class methods. class methods can be called without instantiating an object of that class. instance methods are called from the object, or instance, of a class. think of $this as referring to this instance of the class.
e.g.: $obj = new MyClass();
$obj->myInstanceMethod();
for class (static) methods, there is no instance, therefore, there is not this
e.g.: $returnVal = MyClass::myClassMethod();
you would want to use self instead of this with class methods
let me know if you want anymore clarifications! this is one of the trickier pieces of OO to grasp at first
<?php
class c1
{
public static function f1()
{
return "hello";
}
public static $a=10;
public function f2()
{
echo $this->f1(); //prints "hello"
echo $this->a;//ERROR:Undefined property: c1::$a in C:\wamp\www\class_in_php\example5.php on line 14
}
}
$obj1=new c1;
$obj1->f2();
?>
Why can't we access a static variable of a class using $this or an object of that class???
But we can access a static function of that class using $this or an object of that class.
What is the reason behind such a phenomenon?
You should use self:: instead of $this-> to access static members.
The reason is that $this refers to the current instance of the class, while static members are part of the class itself, not of the instance.
A static variable belongs not to an "instance" but to the class itself. When you have in actual "instance" of the class at runtime, then and only then does the $this pointer make sense: it means "this instance that I find myself inside right now"... how could you use the $this pointer to reference something that doesn't exist outside of an instance?
When I first learned C++ it was with (Metacomco I think) a system that actually used a huge pile of C preprocessor macros to simulate objects and it was very enlightening to see and hence understand that the $this (this in C++) is in fact just an extra parameter passed as the first parameter to all method functions:
this->foo("Hello");
this->bar(42, "Finished");
is actually executed like this:
foo(this_ptr, "Hello");
bar(this_ptr, 42, "Finished");
and inside the foo() function any reference to a method variable such as:
this->status
is nothing more than a reference to a pointer dereferenced variable:
this_ptr->status
So you can see that trying to access a static variable from a this pointer is going to blow because it just isn't a member of that particular chunk of memory. That's how things "used to work" but I think the explanation is still a good one.
Hope that help!
:)
Why can't we access a static variable of a class using $this or an object of that class? But we can access a static function of that class using $this or an object of that class.
Well, we can, however you used the wrong syntax.
Wrong:
echo $this->a;
Right:
$this::$a;
As c1::$a is a static class variable, you need to use the right syntax, that is with double-colon :: and then the dollar-sign ($) to denote the variable: $this::$a.
However, do not get fooled by that syntax too easy, because the reason that
$this->f1()
works while c1::f1() is a static function is because of backwards compatibility as before PHP version 5 there were no static class methods (as those explicitly defined by the static keyword) and with the very first PHP 5 version -> could be used to call static class methods.
However to access static class variables via $this is a PHP 5.3+ syntax feature, so much newer.
Example code (run against multiple PHP versions):
<?php
/**
* #link http://stackoverflow.com/a/24059368/367456
*/
class c1
{
public static function f1()
{
return "hello";
}
public static $a = 10;
public function f2()
{
echo $this->f1(); // prints "hello"
echo $this->a; // Strict Standards: Accessing static property c1::$a as non static
echo $this::$a; // prints "10" (PHP <= 5.2.17: Parse error)
}
}
$obj1 = new c1;
$obj1->f2();
I have a static function being called that is giving a strange error. Here is an example of the php code:
class foo {
public $stat;
public function __construct() {
$this->stat = stat::isValid('two');
}
}
class stat {
protected static $invalidNumbers = array('one', 'two');
function isValid($number) {
return in_array($number, static::$invalidNumbers);
}
}
$foo = new foo();
var_dump($foo->stat);
This code results in the following error:
Fatal error: Access to undeclared static property: foo::$invalidNumbers
However changing static:: to self:: makes the code behave as expected. I was under the impression that in this context using static:: should work.
Why does this error occur using static?
You begin by making a method call in a static context:
stat::isValid('two');
When you do this, PHP "remembers" the context from within which isValid was called specifically so that it can resolve what to bind to when it sees something like static:: inside the method body, determine if some property you are trying to access is visible, and in general be able to implement some OO-related language features.
The actual method isValid is not static, but PHP still allows you to call it using the static method syntax (it does give an E_STRICT warning about that). However, this has the side effect that isValid itself does not participate in modifying the curent calling context for (late) static bindings.
The result: when PHP sees static::$invalidNumbers, it still thinks you are halfway through making a static method call from within the foo class! Once you realize this, it is obvious why static:: resolves to foo:: and it ends up looking for the property at the wrong place.
If you correctly declare isValid as static
static function isValid($number) {
return in_array($number, static::$invalidNumbers);
}
then upon calling the method PHP does update its context internally and manages to bind to the intended member.
You are trying to call the method stat::isValid() statically but have not declared it static. Change the stat class to:
class stat {
protected static $invalidNumbers = array('one', 'two');
// needs to be declared static
static function isValid($number) {
return in_array($number, static::$invalidNumbers);
}
}
Note that, if you add
| E_STRICT
to your error_reporting in php.ini you would see a message like:
Strict standards: Non-static method stat::isValid() should not be called statically, assuming $this from incompatible context in ...
Declare static method properly
Replace
function isValid($number) {
With
public static function isValid($number) {
^--- here
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?