Sequoya
Sequoya

Reputation: 443

How to correctly use static variables in class methods?

I'm trying to do this code in PHP:

class T {

    public $y = 4;

    public function y() { return $this->y; }

    public function q()
    {
        static $j = $this->y;   
        echo $j;
    }
}

$r = new T();
$r->q();

and I get the following error:

Fatal error: Constant expression contains invalid operations in C:\xampp\htdocs\dermaquality\test.php on line 13
static $j = $this->y; 

If I set the value manually, there is no problem, but if I set the value calling y() or $this->y I get that error. I don't know why?

Upvotes: 1

Views: 301

Answers (1)

Vikas Umrao
Vikas Umrao

Reputation: 2615

To assign values to static variables which are the result of expressions will cause a parse error.

static $int = 0;          // correct 
static $int = 1+2;        // wrong  (as it is an expression)
static $int = sqrt(121);  // wrong  (as it is an expression too)

Upvotes: 1

Related Questions