0

Possible Duplicate:
Getting static property from a class with dynamic class name in PHP

Take a quick look before you are going to reading my question:

In PHP we can:

Code:

<?php
    class Foo
    {
        const TOUCH_ME = 1;
        public function __construct()
        {
        }
    }
    $class = 'Foo';
    $object = new $class();
    $type = $object instanceof Foo;
    echo $type;//Expect to 1
?>

Output:

1

And my question is, how can I do:

Code:

<?php
    class Foo
    {
        const TOUCH_ME = 1;
        public function __construct()
        {
        }
    }
    $class = 'Foo';
    $var = $class::TOUCH_ME;
?>

Output:

An error

So, how can I do that? Or am I stupid?

Community
  • 1
  • 1
vietean
  • 2,975
  • 9
  • 40
  • 65
  • 1
    Upgrade to PHP 5.3 or newer and `$class::TOUCH_ME` works fine. – user229044 Dec 09 '11 at 18:26
  • If you just want the constant, you don't need any elaborate workarounds or PHP 5.3. A simple `constant("$class::TOUCH_ME");` will do. – mario Dec 09 '11 at 18:28

2 Answers2

0
php -r ' class Foo { const BAR = 1; } $class = "Foo"; $var = $class::BAR; echo $var; '

// outputs 1

I'm on PHP version 5.3, but I don't see why this wouldn't work in earlier versions of PHP unless it was an issue wrapped up with late static binding:

http://www.php.net/manual/en/language.oop5.late-static-bindings.php

Jonathan Rich
  • 1,740
  • 10
  • 11
0

only possible since PHP 5.3 see http://php.net/manual/en/language.oop5.constants.php

tripplet
  • 335
  • 1
  • 11