2

I'm wondering if it's possible to call a function from a name spaced file.

Currently the code below produces an error. I know it's possible to just pass the whole namespace, but is there a more automated way just using the alias of U?

use Helpers\User as U; $t = call_user_func('U\something', 'test'); var_dump($t);

UPDATE

The way I solved this was by creating a function within that name spaced file that would return the file name spaced.

/**
 *
 * pntfn = Prepend namespace to function name
 *
 * @param $fn
 *
 * @return string
 */
function _pntfn($fn) {
    return __NAMESPACE__.'\\'.$fn;
}

This then let's me do the following in a file

use Helpers\Users as U;

If I wanted to compose (functional programming) a function from my Users namespace file I would do the following;

$get_username_upper = F\compose('strtoupper', U\_pntfn( 'get_username' ));

Not my favorite implementation, but works for now. The con, is that you'd have to add this to all of your name spaced function files.

1
  • Since there's no way can do this, what I did is to use $U = 'Helpers\User' then call_user_func("$U\something", 'test'). Commented May 31, 2016 at 10:38

1 Answer 1

1

The trouble is U is resolved at compile time, so calling:

U\something

Literally becomes:

Helpers\User\something

This might still be invalid, since I know we also have the directive use function, so you may want to check that out as well.

Anyway, the string 'U\something' is a runtime constant, meaning U at this point doesn't actually refer to anything at all. So no, unfortunately this isn't possible.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.