Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable functions with namespaces in PHP

Tags:

namespaces

php

I'm wondering if there is a way to call variable functions with namespaces. Basically I'm trying to parse tags and send them to template functions so they can render html`

Here's an Example: (I'm using PHP 5.3)

 // Main php file
require_once 'template.php';
foreach (array("javascript","script","css") as $tag) {
    echo template\$tag();
}

 // template.php
 namespace template;

 function javascript() { return "Hello from javascript"; }
 function css() { return "Hello from css"; }
 function script() { return "Hello from script"; }

I keep getting Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in ... on line 76

Thanks! Matt

like image 911
Matt Avatar asked Aug 09 '09 01:08

Matt


1 Answers

This will also work, no need for call_user_func, just use the Variable functionsDocs feature:

require_once 'template.php';

$ns = 'template';
foreach (array('javascript', 'script', 'css') as $tag) {
    $ns_func = $ns . '\\' . $tag;
    echo $ns_func();
}
like image 183
GZipp Avatar answered Sep 21 '22 19:09

GZipp