Php import constants from another file

I have a small piece of code that was written in previous version of PHP [not 5.3] and I find it odd for the interpreter to catch a cross use of a constant as a notice message then finally cough up a fatal error when the constant is defined in a file that is different from the one the notice is being reported. That is, for example, I define my constant in file A which is initialized when the program starts

define['SOME_CONSTANT','something'];

and in file B.php

require_once['A.php'];
Call-function-that-uses-fileA's-SOME_CONSTANT

File B is reported with notice message and a fatal error.

The fatal error can be roughly described as

require_once[] [function.require]: Failed opening required ....

in which "...." stands for a long line of included paths that may or maynot be related to the current file B at all. I am grateful for any help or advice you offer.

Is this caused by my use of new PHP version while my code was written in old one ? How can I fix these messages without reinstalling the PHP ?

Edit:

The only reason I would not want to reinstalling the PHP is that because I don't want to always change the PHP whenever I have to work with a new project. Now it may be old, what if later I need to use the latest version, re-downloading the new one and deleting the old one psss?

[PHP 5 >= 5.3.0, PHP 7, PHP 8]

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

PHP can alias[/import] constants, functions, classes, interfaces, traits, enums and namespaces.

Aliasing is accomplished with the use operator. Here is an example showing all 5 kinds of importing:

Example #1 importing/aliasing with the use operator

Note that for namespaced names [fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar], the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace.

PHP additionally supports a convenience shortcut to place multiple use statements on the same line

Example #2 importing/aliasing with the use operator, multiple use statements combined

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

Example #3 Importing and dynamic names

In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.

Example #4 Importing and fully qualified names

Scoping rules for importing

The use keyword must be declared in the outermost scope of a file [the global scope] or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:

Example #5 Illegal importing rule

Note:

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

Group use declarations

Classes, functions and constants being imported from the same namespace can be grouped together in a single use statement.

statement does not load the class file. You have to do this with the statement or by using an autoload function.

Mawia HL

4 years ago

Here is a handy way of importing classes, functions and conts using a single use keyword:

k at webnfo dot com

9 years ago

Note that you can not alias global namespace:

use \ as test;

echo test\strlen[''];

won't work.

xzero at elite7hackers dot net

5 years ago

I couldn't find answer to this question so I tested myself.
I think it's worth noting:



None of above will actually cause errors unless you actually try to use class you tried to import.

me at ruslanbes dot com

6 years ago

Note the code `use ns1\c1` may refer to importing class `c1` from namespace `ns1` as well as importing whole namespace `ns1\c1` or even import both of them in one line. Example:



and you then go into the CLI to test it. You would like to think that this would work, as you type it line by line:

require 'myclass.php';
use my%space%myclass; // should set 'myclass' as alias for 'my%space%myclass'
$x = new myclass; // FATAL ERROR

I believe that this is because aliases are only resolved at compile time, whereas the CLI simply evaluates statements; so use statements are ineffective in the CLI.

If you put your test code into test.php:

it will work fine.

I hope this reduces the number of prematurely bald people.

cl

9 years ago

Something that is not immediately obvious, particular with PHP 5.3, is that namespace resolutions within an import are not resolved recursively.  i.e.: if you alias an import and then use that alias in another import then this latter import will not be fully resolved with the former import.

For example:
use \Controllers as C;
use C\First;
use C\Last;

Both the First and Last namespaces are NOT resolved as \Controllers\First or \Controllers\Last as one might intend.

x at d dot a dot r dot k dot REMOVEDOTSANDTHIS dot gray dot org

9 years ago

You are allowed to "use" the same resource multiple times as long as it is imported under a different alias at each invocation.

For example:



In the above example, "Keller", "Stellar", and "Zellar" are all references to "\Lend\l1\Keller", as are "Lend\l1\Keller", "l1\Keller", and "l3\Keller".

eithed at google mail

1 year ago

Bear in mind that it's perfectly fine to alias namespaces, ie:



can be also written as:



however following will not work:



> PHP Error:  Class "ENamespace\User" not found

ultimater at gmail dot com

6 years ago

Note that "use" importing/aliasing only applies to the current namespace block.



To get the expected behavior, you'd use:
class_alias['SuperCoolLibrary\Meta','Meta'];

ZhangLiang

5 years ago

In Chinese,there is an error in translation:
// 如果不使用 "use \ArrayObject" ,则实例化一个 foo\ArrayObject 对象
it should be
// 如果不使用 "use ArrayObject" ,则实例化一个 foo\ArrayObject 对象

/*********************************************/
中文下翻译有错误
// 如果不使用 "use \ArrayObject" ,则实例化一个 foo\ArrayObject 对象
这句话应该是
// 如果不使用 "use ArrayObject" ,则实例化一个 foo\ArrayObject 对象

tuxedobob

4 months ago

Note that because this is processed at compile time, this doesn't work when running PHP in interactive mode. use commands won't throw an error, but they won't do anything, either.

thinice at gmail.com

11 years ago

Because imports happen at compile time, there's no polymorphism potential by embedding the use keyword in a conditonal.

e.g.:

kelerest123 at gmail dot com

7 years ago

For the fifth example [example #5]:

When in block scope, it is not an illegal use of use keyword, because it is used for sharing things with traits.

Anonymous

9 years ago

The last example on this page shows a possibly incorrect attempt of aliasing, but it is totally correct to import a trait \Languages\Languages\Danish.

dominic_mayers at yahoo dot com

6 years ago

To clarify the distinction between inserting a trait in a class and importing a trait in a namespace, here is an example where we first import and then insert a trait.


but you cant use/call they:

Joey

4 years ago

For those hoping for an easy fix of DRY with {} unfortunately you can't nest it or do anything cool with it. In case you can only have one per use and if you don't have one then the whole use is assumed to be wrapped in brackets. That means if you do have one you can't use , as normal with use!

Not possible:

    use A\B\C\{
            D, E,
            F\{X, Y, Z}
        },
        X\Y\Z,
        H\{
            I\{
                Y\Y\Y\Y\Y,
                Z, H, E
            },
            J\{
                A\{
                    G\H\J
                    B\N
                },
                G\H\J
            }
        };

www.codewars.com

3 years ago

amazing!!

use function strval as numberToString;

var_dump[numberToString[123]];

//print
//string[3] "123"

Dhairya Lakhera

3 years ago

namespace test{

    use test\xyz\tikku;
    use test\xyz\tikku as class_alias;
    use function test\xyz\tikku\foo;
    use function test\xyz\tikku\foo as func_alias;
    use const test\xyz\tikku\ABC;
    use const test\xyz\tikku\ABC as const_alias;

            $obj=new tikku;
    $obj->Display[];  // I am in  test\xyz namespace

    $obj=new tikku\dhairya;
    $obj->Display[];   // I am in test\xyz\tikku namespace

    $obj=new class_alias\dhairya;
    $obj->Display[];   // I am in test\xyz\tikku namespace

    $obj=new \class_alias\dhairya;
    $obj->Display[];  // I am in class_alias namespace

}

namespace test\xyz{

   class tikku{
    function Display[]{
        echo "I am in ".__namespace__." namespace
";
    }
   }
}

namespace test\xyz\tikku{

   class dhairya{
    function Display[]{
        echo "I am in ".__namespace__." namespace
";
    }
   }
}

namespace class_alias{

   class dhairya{
    function Display[]{
        echo "I am in ".__namespace__." namespace
";
    }
   }
}

Chủ Đề