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\');
$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.
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();
}
}
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.
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();
Just use the Class method using this foobar->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?