gpt4 book ai didi

php - 如何在 Symfony 4 中使用简单的函数?

转载 作者:行者123 更新时间:2023-12-04 14:19:02 25 4
gpt4 key购买 nike

我想在 Symfony 4 中使用一个简单的函数,像这样:

src/Service/Utils.php

<?php

namespace App\Service;

/**
* @param string $attr
*
* @return bool
*/
function attributNilTrue($attr): bool
{
return json_encode($attr) === '{"@attributes":{"nil":"true"}}';
}

一些/其他/file.php

use function App\Service\attributNilTrue;

if (attributNilTrue($foo['bar'])) {
// Do something...
}

但是我得到以下错误:

The autoloader expected class "App\Service\Utils" to be defined in file "/var/www/interop/vendor/composer/../../src/Service/Utils.php". The file was found but the class was not in it, the class name or namespace probably has a typo.

有没有一种方法可以做到这一点而不必创建 Utils 类?

最佳答案

您可以使用 autoloader files key in composer .

在你的 composer.json 文件中包含如下内容:

{
"autoload": {
"files": ["src/utility_functions.php"]
}
}

(其中 src/utility_functions.php 是包含您的函数定义的文件)。

转储您的自动加载器 (composer dump-autoload),以便将其合并到您的自动加载器文件中,并且您在此文件中定义的任何函数都将在每次请求时可用。

您的典型 Sf4 将已经包含一个 PSR4 条目,因此您必须添加自己的条目。最终结果或多或少是这样的:

"autoload": {
"psr-4": {
"App\\": "src/"
},
"files": [
"src/utility_functions.php"
]
},

关于php - 如何在 Symfony 4 中使用简单的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56992865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com