tags:

views:

46

answers:

2

How can I access static php variable with custom class name. In class c1 method hi() I need to access static variable of its child class. PHP < 5.3

class c1{
  function hi(){
    $cn=get_class($this);
    echo $cn::$b; //need echo 5 here, but error
  }
}
class c2 extends c1{
  static public $b=5;
}

$c2=new c2();
$c2->hi();
+1  A: 

One way that popped into my mind is eval( "return $cn::\$b;" ) but use with care. Eval can create some nasty security holes if the input isn't sanitized correctly.

Kendall Hopkins
+3  A: 

You can use ReflectionClass:

$cn=get_class($this);
$cl=new ReflectionClass($cn);
echo $cl->getStaticPropertyValue('b');

Or get_class_vars():

$cn=get_class($this);
$props=get_class_vars($cn);
echo $props['b'];
Lukman
what about performance? Do I really need to create object just to get value of one property?
codez
edited with second choice ;)
Lukman