Re: runtime access to static variable
| From: | Jack Bates | Date: | Thu, 18 Dec 2008 02:19:16 +0000 |
| Subject: | Re: runtime access to static variable | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-284761@lists.php.net to get a copy of this message | ||
> this does beg the question why don't you know the classname at runtime..
> seems to be a slight design flaw and may make sense for you to post the
> full problem (you must have chosen to implement this for a reason..)
The full problem is: I started off with a "DeployTask" for deploying a
new instance of my web project to DreamHost:
http://cgi.sfu.ca/~jdbates/tmp/php/200812170/DeployTask.class.phps
(It is a "task" in the symfony framework, but basically the
DeployTask::execute() method gets called)
The task takes about thirty minutes to run, so I broke it up into steps.
After each step, it updates a database row so that a user who started
the task through a web interface can monitor its progress.
Great so far. Now I decided to create an "UpdateTask" for updating
deployed instances to the latest version of my code:
http://cgi.sfu.ca/~jdbates/tmp/php/200812170/UpdateTask.class.phps
Of course it also takes a long time to run, so my first iteration just
extends the DeployTask and defines different steps. UpdateTask inherits
DeployTask::execute(), which drives the steps and updates the database.
Unfortunately, in the inherited DeployTask::execute(), "self::$STEPS"
does not refer to UpdateTask::$STEPS, it refers to DeployTask::$STEPS
: (
I gather with "late static bindings" in PHP 5.3, "static::$STEPS" does
what I want? Anyway, DeployTask::execute() is not static, so I know
whether $this is an instance of DeployTask of UpdateTask:
"get_class($this)" returns it. Which brought me to my contrived example:
ket% cat test.php
<?php
class Test
{
public static
$STEPS = array(
'foo',
'bar');
}
$className = 'Test';
var_dump($className::$STEPS);
ket%
Except that in real life, "$className = get_class($this)"
> Check this out:
> http://us2.php.net/manual/en/language.oop5.static.php
>
> It actually won't work until 5.3.0 when they add late static binding.
I ran my contrived example with PHP 5.3alpha3, and it worked!
"$className::$STEPS" is not a parse error in 5.3, which is cool : )
Except that in 5.3, I will probably just use "static::$STEPS" anyway : P
In the meantime, I will probably use reflection as suggested:
// HACK: Use "static::$STEPS" in PHP 5.3:
// http://php.net/oop5.late-static-bindings
$class = new ReflectionClass($this);
$steps = $class->getStaticPropertyValue('STEPS');