开发者

PHP: Getting a value of a static variable of an unknown subclass [duplicate]

This question already has answers here: 开发者_开发技巧 Closed 11 years ago.

Possible Duplicate:

From the string name of a class, can I get a static variable?

Somewhere in a parent class, I need to find the value of a static variable of one of the possible child classes, determined by the current instance.

I wrote:

  $class = get_class($this);
  $value = isset($class::$foo['bar']) ? $class::$foo['bar'] : 5;

In this example, the subclass whose name is in $class has a public static $foo.

I know using $class::$foo['bar'] is not a very beautiful piece of code, but it gets the job done on PHP 5.3.4.

In PHP 5.2.6 though, I am getting a syntax error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ')'

Is there an alternative way that would work on PHP 5.2.4+ that would get the same thing done?


EDIT: Reflection is better.

You can try the get_class_vars method. No access to PHP 5.2.6, but this works in 5.2.11...

class Test {
    public static $foo;

    function __construct() {
        echo("...Constructing...<br/>");
        Test::$foo = array();
        Test::$foo['bar'] = 42;
    }

    function __toString() {
        return "Test";
    }
}


$className = 'Test';
$class = new $className();

$vars = get_class_vars($className);

echo($vars['foo']['bar'] . "<br/>");

Output:

...Constructing...
42


The reason that this does not work in PHP 5.2, is because before PHP 5.3 you are not allowed to use variables in the classname. So, if possible use eval for this.

eval('$result = ' . $c . '::$foo[\'bar\'];');
echo $result;

Otherwise, you're forced to use a function in the child class to receive the value. For example:

class MyParent {
    public function __construct() {
        $var = $this->_getVariable();
        echo $var['bar'];
    }
}

class MyChild extends MyParent {
    static $var = array('bar' => 'foo');

    protected function _getVariable() {
        return self::$var;
    }
}

new MyChild();


class Bar1 {
    static $var = array('index' => 'value');
}
class Bar2 extends Bar1 {
}
class Foo extends Bar2 {
    static $var = array('index' => 'value in Foo');
    public function __construct() {
        echo parent::$var['index'];
    }
}

$foo = new Foo();

will output 'value', but not 'value in Foo'

Hope, that's what you are looking for.


You can get class static/call static method in the class you are working in using self key word or for parent class using parent. You can get that error on php 5.2.6 because of changes in get_class function in PHP 5.3.0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜