11

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

1
  • You're using the Variable functions wrong, it needs to be a variable, not a string and variable. Commented Feb 14, 2012 at 9:41

4 Answers 4

7

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();
}
Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

Needed a parameter. Here's how to do that. echo call_user_func('template\\'.$tag, $params);
1

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

3 Comments

::? Really... Someone either didn't do their homework or simply has no understanding of the difference between a namespace and a static member of a class.
Thanks! Only slightly off though! I appreciate the help though.
@Andrew you were right. I messed it up when is pasted the code. thank you
0

Try this

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

$test = new $test2;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.