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();

2 Answers 2

4

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

what about performance? Do I really need to create object just to get value of one property?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.