views:

91

answers:

2

I'm having the following scenario:

class A { public static $arr=array(1,2); }
class B extends A { public static $arr=array(3,4); }

Is there any way to combine these 2 arrays so B::$arr is 1,2,3,4?

I don't need to alter these arrays, but I can't declare them als const, as PHP doesn't allow const arrays.http://stackoverflow.com/questions/ask The PHP manual states, that I can only assign strings and constants, so parent::$arr + array(1,2) won't work, but I think it should be possible to do this.

+3  A: 

You're correct, you can only assign literals and constants when declaring a static variable. The work-around would be to assign the value in code just after the class is declared. In Java you could do this nicely with a static initialiser, but PHP doesn't support those either, so we have to define and call a method ourselves:

class A { public static $arr=array(1,2); }
class B extends A {
  public static $arr;
  public static function init() {
    self::$arr = array_merge(parent::$arr, array(3,4));
  }
}; B::init();

Also note the use of array_merge instead of the union (+) operator - the union operator won't combine the arrays as you intend, as they have identical numerical keys - the first is array(0=>1, 1=>2), second is array(0=>3, 1=>4); the union of them will only contain each key once, so you'll either end up with (1,2) or (3,4) depending on the order you union them.

Chris Smith
Doh, you beat me. Still I like my solution more since there isn't an init() dependancy.
Typeoneerror
I just used array(1,2) as an example, in the project it's an associative array so + would work.
tstenner
Can't use `this` in static context. Try static/self.
webbiedave
@webbiedave - D'oh, good spot. Fixed :)
Chris Smith
@webbiedave You're right, it should be `self::$arr`.
tstenner
+1  A: 

Yes, you just need to get a bit fancy as you won't be able to define a static variable.

<?php

class A 
{
    public static $arr = array(1, 2);
    public static function getArr(){ return self::$arr; }
}

class B extends A 
{
    public static $arr = array(3, 4);
    public static function getArr(){ return array_merge(parent::$arr, self::$arr); }
}


print_r( A::getArr() );
print_r( B::getArr() );

Output:

Array
(
    [0] => 1
    [1] => 2
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Also good since you can access the original arrays too:

print_r( A::$arr );
print_r( B::$arr );

Array
(
    [0] => 1
    [1] => 2
)
Array
(
    [0] => 3
    [1] => 4
)
Typeoneerror
Also a good answer, but the arrays will be merged every time I want to access them and inheriting if from B should work, `getArr()` would have to call `parent::getArr()`, not `parent::$arr`.
tstenner
True. I don't think inheritance and static properties make a lot of sense anyway. Whatever works though.
Typeoneerror