Guaycuru
Guaycuru

Reputation: 1350

Undefined class constant 'self::STRING'

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!

Upvotes: 1

Views: 5511

Answers (1)

MrSoundless
MrSoundless

Reputation: 1384

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'

Upvotes: 1

Related Questions