views:

814

answers:

5

Hello everyone. Here's my question for today. I'm building (for fun) a simple templating engine. The basic idea is that I have a tag like this {blog:content} and I break it in a method and a action. The problem is when I want to call a static variable dynamically, I get the following error .

Parse error: parse error, expecting `','' or `';''

And the code:

 $class = 'Blog';
 $action = 'content';
 echo $class::$template[$action];

$template is a public static variable(array) inside my class, and is the one I want to retreive.

A: 

I'am not sure what i'm doing but give it a try:

echo eval( $class . "::" . $template[$action] );
palindrom
Yep that should to the job. But I've forgot to mention eval is my last option :D .Not of fan of eval.
Bdesign
+3  A: 

You may want to save a reference to the static array first.

class Test
{
    public static $foo = array('x' => 'y');
}

$class  = 'Test';
$action = 'x';

$arr = &$class::$foo;
echo $arr[$action];

Sorry for all the editing ...

EDIT

echo $class::$foo[$action];

Seems to work just fine in PHP 5.3. Ahh, "Dynamic access to static methods is now possible" was added in PHP 5.3

Philippe Gerber
Yields: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
soulmerge
Works fine in PHP 5.3. Let me check.
Philippe Gerber
This is giving `Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM`
RaYell
That's nice, didn't know that.
soulmerge
It seems PHP 5.3 has some nice new features ( like this and NAMESPACE ).
Bdesign
A: 

You cannot do that without using eval(). $class::$template (even if it was valid syntax in PHP), would reference the static variable called $template, you would actually need variable variables ($class::$$template), which is again not valid PHP syntax (you cannot access anything from a dynamic class name in PHP, IIRC).

I would recommend checking the variables for valid names before usng eval(), though (the regex is copied from the PHP manual):

if (!preg_match('[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*', $class)) {
    throw new Exception('Invalid class name (' . $class . ')');
}
soulmerge
You're right, it seems Php is looking for $template . Thanks for the making this clear.
Bdesign
Actually, you can :)
Kuroki Kaze
Yes, you can, you are right. I'll leave the answer for reference.
soulmerge
+5  A: 

What about get_class_vars ?

class Blog {
    public static $template = array('content' => 'doodle');
}

Blog::$template['content'] = 'bubble';

$class = 'Blog';
$action = 'content';
$values = get_class_vars($class);

echo $values['template'][$action];

Will output 'bubble'

Kuroki Kaze
Woohoo, this works. Thank you very much, saved me.
Bdesign
A: 

As with everything in PHP, there are a lot of ways to skin the same cat. I believe the most efficient way to accomplish what you want is:

call_user_func(array($blog,$template));

See: http://www.php.net/manual/en/function.call-user-func.php

Warren Benedetto