Matt
Matt

Reputation: 22901

Variable functions with namespaces in 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

Upvotes: 11

Views: 3852

Answers (4)

Maxim
Maxim

Reputation: 321

Try this

$p = 'login';
namespace App\login; 
$test2 = '\App\\'.$p.'\\MyClass';

$test = new $test2;

Upvotes: 0

Andrew Moore
Andrew Moore

Reputation: 95334

Sure you can, but unfortunately, you need to use call_user_func() to achieve this:

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

Namespaces in PHP are fairly new. I'm sure that in the future, they will fix it so we won't require call_user_func() anymore.

Upvotes: 5

GZipp
GZipp

Reputation: 5416

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();
}

Upvotes: 7

Gabriel Sosa
Gabriel Sosa

Reputation: 7956

try with

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

 // template.php
 namespace template;

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

you have some info here

Upvotes: 1

Related Questions