Monday, November 14, 2011

Don't use "static" variables in PHP objects


Why you never should use "static" variables in non-static PHP objects just to cache variable:

<?php

class Field
{
 private $x = 1;

 public function getZZZ()
 {
  static $zzz = array();
  if (empty($zzz)) $zzz[] = $this->x*2;
  return $zzz;
 }

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

 public function setX($x)
 {
  $this->x = $x;
 }
}

$aField = new Field();
$bField = new Field();
$aField->setX(5);
var_dump($aField->getZZZ());
var_dump($bField->getZZZ());
$bField->setX(2);
var_dump($bField->getZZZ());
var_dump($aField->getZZZ());


Result: array will always contain "10". Even when you doing it for object aField, object bField will be affected, and it is horrible and I'm sure it will be the reason of bugs in a lot of scripts.
You can vote for fixing this bug here: https://bugs.php.net/bug.php?id=53666

1 comment: