1

I've been struggling for a few days now with a completely weird bug: Here's the scenario (bear with me):

I have one "framework" class, which I'll call F. I have some simple classes that extend F, one of them I'll call P.

So what I have is:

class F {
    [...]
    protected static $_tabela;
    [...]
    final public static function _Tabela() {
        return static::$_tabela;
    }
    public static function Consultar() {
        echo static::_Tabela();
    }
}

class P extends F {
    protected static $_tabela = 'produtos';
}

And when I call P::Consultar(); I get this error that makes no sense to me:

Fatal error: Undefined class constant 'self::STRING' in [...]/F.inc.php on line X

Where X is the body of the _Tabela() method.

So, I've tried changing the variable name ($_tabela). I tried saving the class name via get_called_class():

$class = get_called_class()
return $class::$_tabela;

But got the same error.

Also, the error message is completely useless, I'm not trying to access a class constant, but instead a class static property!

Googling the error message also gave me no useful results.

Edit: Thanks everyone for the answers! I found the problem, and it had nothing to do with the code I was looking at. Turns out there was an error in the definition of the P class, so when I tried calling static::Consultar, PHP parsed the class and complained about the error!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Guaycuru
  • 1,320
  • 1
  • 11
  • 12
  • Some code where you see this error would be helpful – Artem L Dec 28 '12 at 15:38
  • When asking about errors you should always include the full error message and the offending line and the line above it. – Jason McCreary Dec 28 '12 at 15:39
  • 2
    Your code does not make any sense, could you post portions of the original code that matters? – dbf Dec 28 '12 at 15:41
  • Specify your PHP version, as @MrSoundless answer says, this should work on PHP 5.3 and up. Also... don't wanna ask why on earth are you trying to do this, but I leave some word of sanity, stop using statics! – fd8s0 Dec 28 '12 at 16:26
  • I have a suspicion. Try replacing static with self, in that context it should have the same effect you are expecting, except it should work. It might be a bug introduced in some version, we could check if there's something reported, but it works on 5.3.10. – fd8s0 Dec 31 '12 at 10:02
  • If you found the solution, _post it as such_ please. – Lightness Races in Orbit Mar 03 '13 at 22:17

1 Answers1

1

If you're using PHP version >= 5.3.0 , you can do this:

<?php
class F {
    protected static $_tabela = 'a';

    final public static function _Tabela() {
        $s = new static();
        return $s::$_tabela;
    }
    public static function Consultar() {
        $s = new static();
        echo $s::_Tabela();
    }
}

class P extends F {
    protected static $_tabela = 'produtos';
}

echo P::Consultar(); // echos 'produtos'
MrSoundless
  • 1,246
  • 2
  • 12
  • 34