Daenu Daenu - 2 years ago 140
PHP Question

class public variable calls compatible in PHP 7.0 and PHP 5.6

In PHP 5.6:

When being inside a class we usually declare & call a public class variable like this:

class MyClass
* @var int
public $myVar = 0;

// call it in a public function:
public function myFunction()
return $this->myVar;


I call the function like this:


In PHP 7.0 that code throws a fatal error:

Using $this when not in object context

After changing my PHP version back to 5.6 again, the error was gone.


I have to admit that after reading the manual and changes from 5.6 to 7.0 I don't get it.

  1. How do we declare and call public class variables in PHP 7.0?

  2. How do we write this code to be compatible between 5.6 and 7.0?

Edit after comments:

So why then a static call on a non static method works in 5.6?

Answer Source

In I'm loading maybe func() like this:

 obj::func();  // Wrong, it is not static method

but can also be

$obj = new Obj();  // correct

You can not invoke method this way because it is not static method.


You should instead use:


If however you have created a static method something like:

static $foo; // your top variable set as static

public static function foo() {
    return self::$foo;

then you can use this:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download