0

Is there any way to access static property via variable that holds property name(Except of ReflectionClass and eval())?

class WhateverClass
{
    public static $test = array('1','2');
    public static $other = array('3','4');
}
$propName = 'test';
var_dump(WhateverClass::$propName);
3
  • I think you need to use double $ syntax for this. Look up variable variables in PHP's manual. Commented Dec 19, 2013 at 17:03
  • 1
    did you try WhateverClass::${$propName} ? Commented Dec 19, 2013 at 17:04
  • I tried something like ` WhateverClass::{$propName}`. I totally forgot about $$. Thanks all. Commented Dec 19, 2013 at 19:26

2 Answers 2

1

The following should work:

var_dump(WhateverClass::$$propName);

This is known as variable variables

I'd try to minimise my use of that technique though, it could get very confusing very quickly if overused.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use "variable variables".

$propName = 'test';
var_dump(WhateverClass::$$propName);

Note the two $. That tells PHP to look for variable named... whatever $propName contains.

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.