use函数不会在PHP中导入函数 [英] use function doesn't import functions in PHP

查看:100
本文介绍了use函数不会在PHP中导入函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能使用



composer.json

  {
autoload:{
psr-4:{
My\\ \:
}
}
}

full.php

 <?php 

命名空间My\Full ;

函数functionName()
{
echo'Hello Stackoverflow';
}

index.php

 <?php 

需要'vendor / autoload.php';

使用函数My\Full\functionName作为func;

func();






注意:我知道我可以要求该文件,但我想知道是否可以不这样做。

解决方案

使用函数不包含任何文件或函数定义,它只是为完全限定的函数名称起别名,这意味着在调用函数时无需指定名称空间。



在您的示例中,您正在使用composer,它非常适合自动包含文件,但是来自 https://www.php-fig.org/psr/psr-4/ PSR-4是


从文件
路径自动加载类的规范


它不会自动加载功能或不符合要求的文件



但是您可以使用composer在这种情况下自动包含文件。您需要更新composer.json,然后运行 composer dumpautoload



composer.json

  {
autoload:{
files:[ full.php]
}
}

其余的都可以保持不变,应该可以使用


Can't import functions using the use function keywords described in PHP.net. Recreating the example locally is returning a PHP Fatal error: Uncaught Error: Call to undefined function.


composer.json

{
    "autoload": {
        "psr-4": {
            "My\\": ""
        }
    }
}

full.php

<?php

namespace My\Full;

function functionName()
{
    echo 'Hello Stackoverflow';
}

index.php

<?php

require 'vendor/autoload.php';

use function My\Full\functionName as func;

func();


Note: I understand I can require the file, but I wanted to know if it was possible without doing so.

解决方案

use function does not include any files or function definitions it simply aliases a fully qualified function name meaning when you call the function you don't need to specify the namespace.

In your example you are using composer which is great for automatically including files however from https://www.php-fig.org/psr/psr-4/ PSR-4 is

a specification for autoloading classes from file paths

It does not autoload functions or files which don't conform to this specification.

You can however use composer to automatically include files for situations like this. You need to update your composer.json then run composer dumpautoload

composer.json

{
    "autoload": {
        "files": ["full.php"]
    }
}

The rest of your can then remain unchanged and it should work.

这篇关于use函数不会在PHP中导入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆