2

Here's a simplfied version of the classes I'm dealing with

class A {
   static protected function getVal() {
              return self::$valB;
            }
}
class B extend A {
   static protected $valB = 'Hello';
}
B::getVal(); // Hello

Should this work in php version 5.2.17 or do I have it setup wrong. I'm currently getting an error saying that it can't find A::$valB.

hakre
  • 193,403
  • 52
  • 435
  • 836
Clutch
  • 7,404
  • 11
  • 45
  • 56

2 Answers2

3

Requires late static binding, which is present in PHP 5.3.0 and later.

http://us3.php.net/manual/en/language.oop5.late-static-bindings.php

In getVal, you'd want to use return static::valB; instead of return self::valB;

damianb
  • 1,224
  • 7
  • 16
1

First, your code syntax is wrong. Start by fixing it:

class A {
   static protected function getVal() {
       return self::$valB;
   }
}
class B extends A {
   static protected $valB = 'Hello';
}
B::getVal();

Now, this will never work because getVal is protected. Unless you call it from A or one of its child, it won't work.

The self keyword resolves to the class that calls it. Since self is used in A: self == A.

You will need to use late static bindings to fix it:

return static::$valB;

Lastly, I'd recommend you also declare $valB in A to avoid fatal errors:

class A {
    static protected $valB;
    static protected function getVal() { ... }
}
netcoder
  • 66,435
  • 19
  • 125
  • 142
  • The reason for $valB being declared in B is because there will be a B.C. D, E classes that will extend A that will all have different values for $valB. The static call works like a charm but in production only PHP v5.2 is available. Maybe this should have been the question in the first place. – Clutch Jun 03 '11 at 21:16
  • @Clutch: Yes, I figured you'd implement `$valB` in sub-classes, but keep in mind that this is a "language feature", other languages will not allow this (see [this answer](http://stackoverflow.com/questions/6165135/this-in-php-is-bound-dynamically-right/6165380#6165380)). As for 5.2, there is a no workaround, unfortunately. – netcoder Jun 03 '11 at 21:22
  • @Clutch You should try convincing either your employer or client to update to PHP 5.3, here's some ammo: PHP 5.2 is unsupported now by Zend and no longer provided with security patches. :) – damianb Jun 04 '11 at 00:16