1

I'm trying every variation of the following to refer to a static property:

get_called_class()::$$prop

I've tried this:

${get_called_class()}::$$prop

I've tried many things, but can't seem to get it.

I know I can just do this:

$className = get_called_class();
$className::$$prop

BUT, that means an extra line of code. Surely there must be a way for the language to make this work on the same line. Anyone have a solution?

(By the way, the static property is protected, so it fails with ReflectionClass::getStaticPropertyValue.)

12
  • Did you try (get_called_class())::$$prop Commented Dec 31, 2013 at 19:17
  • 5
    Please don't do this. Also, I would recommend burning the machine, which contains this code, before it lays eggs. Commented Dec 31, 2013 at 19:19
  • 1
    If something is so fundamentally hard, maybe you shouldn't be doing it in the first place. Commented Dec 31, 2013 at 19:21
  • @tereško: Why the assumption about the surrounding code? Framework level implementations often stretch a language. Consider it was the frameworks that have driven the demand for so many improvements in recent years to accommodate what used to require ugly hacks. I'm doing something clever here that you can't see. Promise! Commented Jan 1, 2014 at 2:10
  • 1
    @FriendlyDev, our dear friend teresko has a (well-founded) dislike for most things static. Usually static things are a code smell that you should be careful to avoid unless there are better (PHP-centric) ways. Without any context to go on, the code as given is scary bad with regard to conceptual not-shooting-one's-self-in-the-foot-ness. Commented Jan 1, 2014 at 3:22

1 Answer 1

2

Without understanding any additional context here, you don't need to actually invoke get_called_class to poke at LSB-resolved static properties. Instead, use the static keyword to automagically resolve the currently called static class name.

class A {

    static $foo = 'from a';

    public static function test($property) {
        echo static::$$property, "\n";
    }

}

class B extends A { static $foo = 'from b'; }
class C extends A { static $foo = 'from c'; }

Example from the PHP interactive prompt:

php > include '/tmp/get_called_class.php';
php > A::test('foo');
from a
php > B::test('foo');
from b
php > C::test('foo');
from c
php > 
Sign up to request clarification or add additional context in comments.

1 Comment

Why of course! Thanks for the reminder. I feel sheepish now. :D

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.