Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import/use a namespaced function in PHP

Tags:

namespaces

php

I've got a namespaced file called test.php with a function and a class:

namespace Test;
function testFunc(){}
class TestClass{}

Then if, in another file I "use" both of these namespace elements, the class works but not the function:

use Test\testFunc,
    Test\TestClass;

include "test.php";
new TestClass();
testFunc();

The TestClass object is created fine, but I get a fatal error for testFunc():

Fatal error: Call to undefined function testFunc()

I thought functions were supported with namespaces. What am I doing wrong?

EDIT: Explanation here - http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse

like image 906
Gnuffo1 Avatar asked Oct 25 '22 15:10

Gnuffo1


1 Answers

See http://php.net/manual/en/language.namespaces.rules.php with particular attention to:

<?php
namespace A;
use B\D, C\E as F;

// function calls

foo();      // first tries to call "foo" defined in namespace "A"
            // then calls global function "foo"

\foo();     // calls function "foo" defined in global scope

my\foo();   // calls function "foo" defined in namespace "A\my"

F();        // first tries to call "F" defined in namespace "A"
            // then calls global function "F"

And

// static methods/namespace functions from another namespace

B\foo();    // calls function "foo" from namespace "A\B"

B::foo();   // calls method "foo" of class "B" defined in namespace "A"
            // if class "A\B" not found, it tries to autoload class "A\B"

D::foo();   // using import rules, calls method "foo" of class "D" defined in namespace "B"
            // if class "B\D" not found, it tries to autoload class "B\D"

\B\foo();   // calls function "foo" from namespace "B"

\B::foo();  // calls method "foo" of class "B" from global scope
            // if class "B" not found, it tries to autoload class "B"
like image 126
Treffynnon Avatar answered Oct 27 '22 04:10

Treffynnon