5

Is there a way to get a PHP namespace to allow for calling functions within a namespace as if they were global?

Example:

handle()

Rather than:

prggmr\handle()

Here is my example code:

<?php
require_once 'prggmr/src/prggmr.php';

prggmr\handle(function() {
  echo 'This is a test scenario';
}, 'test');

prggmr\signal('test');

Aliasing does not work for functions:

<?php
require 'prggmr/src/prggmr.php';
use prggmr\handle;

handle(function(){
    echo "Test";
}, "test");

Results:

Fatal error: Call to undefined function handle()

3 Answers 3

2

From my understanding this excerpt from the documentation says it's not possible ...

Neither functions nor constants can be imported via the use statement.

Source:

http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse

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

Comments

2

Not for a whole namespace, no. But for single names, you can do

use p\handle;

which aliases p\handle to just handle.

1 Comment

Hi thanks I have tried this. The thing is that the main file is namespaced: prggmr, this is giving me an undefined: ---- <?php use prggmr as p; use p\handle as handle; handle(function() {echo 1;}, 'hey'); signal('hey'); --- I have also tried \handle as a global but that wouldn't make sense.
0

Thought I'd add an answer for modern PHP as I recently learned that:

Before PHP 5.6 neither functions nor constants can be imported via the use statement. As of PHP 5.6 aliasing or importing function and constant names is allowed.

So your second code sample should work just fine these days.

Also worth mentioning that you can define a block scope for PHP namespaces, though it's discouraged. So this would work:

<?php
require_once 'prggmr/src/prggmr.php';

namespace prggmr {
    handle(function() {
      echo 'This is a test scenario';
    }, 'test');

    signal('test');
}

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.