Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP static variables in an abstract parent class: question is in the sample code!

Tags:

oop

php

static

Quick code with the question included:

abstract class ClassParent {
    public static $var1 = "ClassParent";
}

class ClassChild1 extends ClassParent{
    public static function setvar1(){
        ClassChild1::$var1 = "ClassChild1";     
    }
}

class ClassChild2 extends ClassParent{
    public static function setvar1(){
        ClassChild2::$var1 = "ClassChild2";
    }
}


ClassChild1::setvar1();

echo ClassChild2::$var1;
// Returns "ClassChild1". Shouldn't this still be "ClassParent"?

I am assuming that the above is expected behaviour and not a PHP bug. In that case, how could I declare a static variable in the parent class which will be handled separately for the child classes. In other words, I want to have separate static values PER CHILD CLASS. Must I declare the static variable specifically in the child classes or is there perhaps another way?

Thanks!

like image 261
Aron Avatar asked Apr 01 '11 12:04

Aron


1 Answers

EDIT: On further investigation, I think what you're asking is not directly possible, even with late static binding. Actually, I am a little surprised.

The answer to this question provides some workarounds.

Original answer:


In a parent class, if you refer to a static variable in the form:

self::$var

It will use that same variable in all inherited classes (so all child classes will be still accessing the variable in the parent class).

This is because the binding for the self keyword is done at compile-time, not run-time.

As of PHP 5.3, PHP supports late static binding, using the static keyword. So, in your classes, refer to the variable with:

static::$var

And 'static' will be resolved to the child class at run-time, so there will be a separate static variable for each child class.

like image 165
Lauren Avatar answered Oct 05 '22 22:10

Lauren