Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the PHP equivalent of a static variable in other languages?

Tags:

php

final

I'm wondering if PHP has a type of variable in classes that functions like static in other languages. And by that I mean all objects of the same class use the same variable and when it's updated on one it's updated on every one. Static is close because it is shared throughout all objects but I need to be able to update it. Will I have to use globals for this?

like image 602
fent Avatar asked Jul 29 '09 05:07

fent


3 Answers

The correct answer is that there is no equivalent in PHP to final, but static seems like what you wanted in the first place anyway.

static has the property that it will have the same value across all instances of a class, because it is not tied to a particular instance.

You will need to use the :: operator to access it, because being static, you cannot use ->.

like image 145
thomasrutter Avatar answered Nov 03 '22 18:11

thomasrutter


I think static is what you want. You can update a static variable, you just have to do it in a "static context" (ie. using the :: operator.

class Class1 {
    protected static $_count = 0;

    public function incrementCount() {
        return self::$_count++;
    }
}

$instance1 = new Class1();
$instance2 = new Class1();
var_dump($instance1->incrementCount(), $instance2->incrementCount());

will output:

int 0

int 1

like image 30
Brenton Alker Avatar answered Nov 03 '22 18:11

Brenton Alker


You can update static properties:

class A {
   protected static $_foo = 0;

   public function increment()
   {
       self::$_foo++;
   }   

   public function getFoo()
   {
       return self::$_foo;
   }
}


$instanceOne = new A();
$instanceTwo = new A();


$instanceOne->getFoo(); // returns 0

$instanceTwo->increment();

$instanceOne->getFoo(); // returns 1
like image 1
jason Avatar answered Nov 03 '22 16:11

jason