使用vlucas/phpdotenv但是在database里面无法使用$_ENV

tzbob888

问题描述

试了一下
1.getenv() env()都可以使用 唯独 $_ENV会报错
2.$_ENV database.php里面无法读取,但是控制器里面可以使用 echo var_dump输出

env可能是使用了Illuminate\Support\Env才ok的,这里不做讨论,只是想弄清楚为什么 $_ENV会报错,是启动顺序的问题?但是bootstrap.php里面已经在安装dotenv的时候自动做了设置啊

这是bootstrap.php

use Dotenv\Dotenv;
use support\Log;
use Webman\Bootstrap;
use Webman\Config;
use Webman\Middleware;
use Webman\Route;
use Webman\Util;
use Workerman\Events\Select;
use Workerman\Worker;

$worker = $worker ?? null;

if (empty(Worker::$eventLoopClass)) {
Worker::$eventLoopClass = Select::class;
}

set_error_handler(function ($level, $message, $file = '', $line = 0) {
if (error_reporting() & $level) {
throw new ErrorException($message, 0, $level, $file, $line);
}
});

if ($worker) {
register_shutdown_function(function ($startTime) {
if (time() - $startTime <= 0.1) {
sleep(1);
}
}, time());
}

if (class_exists('Dotenv\Dotenv') && file_exists(base_path(false) . '/.env')) {
if (method_exists('Dotenv\Dotenv', 'createUnsafeMutable')) {
Dotenv::createUnsafeMutable(base_path(false))->load();
} else {
Dotenv::createMutable(base_path(false))->load();
}
}

这是database.php
return [
// 默认数据库
'default' => 'mysql',

// 各种数据库配置
'connections' => [
    'mysql' => [
        'driver'      => 'mysql',
        'host'        => getenv('DB_HOST'),
        'port'        => getenv('DB_PORT'),
        'database'    => env('DB_DATABASE'),
        'username'    => $_ENV['DB_USERNAME'],
        'password'    => $_ENV['DB_PASSWORD'],
        'prefix'      => $_ENV['DB_PREFIX'],
        'unix_socket' =>  '',
        'charset'     => 'utf8mb4',
        'collation'   => 'utf8mb4_0900_ai_ci',
        'strict'      => true,
        'engine'      => null,
    ],
],

];

程序代码

问题能解决但是想知道原因
解决方式1  variables_order = "GPCS"  改为 variables_order = "EGPCS"  在php.ini中
解决方式2 使用 env()    由Illuminate\Support\Env 提供
解决方法3 使用 $_SERVER    如果不想改php.ini的话

报错信息

PHP Warning:  Undefined array key "DB_USERNAME" in C:\www1\kw_shop\config\database.php on line 26

Warning: Undefined array key "DB_USERNAME" in C:\www1\kw_shop\config\database.php on line 26
PHP Warning:  Undefined array key "DB_PASSWORD" in C:\www1\kw_shop\config\database.php on line 27

Warning: Undefined array key "DB_PASSWORD" in C:\www1\kw_shop\config\database.php on line 27
PHP Warning:  Undefined array key "DB_PREFIX" in C:\www1\kw_shop\config\database.php on line 28

Warning: Undefined array key "DB_PREFIX" in C:\www1\kw_shop\config\database.php on line 28
PHP Warning:  Undefined array key "DB_USERNAME" in C:\www1\kw_shop\config\database.php on line 26

Warning: Undefined array key "DB_USERNAME" in C:\www1\kw_shop\config\database.php on line 26
PHP Warning:  Undefined array key "DB_PASSWORD" in C:\www1\kw_shop\config\database.php on line 27

Warning: Undefined array key "DB_PASSWORD" in C:\www1\kw_shop\config\database.php on line 27
PHP Warning:  Undefined array key "DB_PREFIX" in C:\www1\kw_shop\config\database.php on line 28

操作系统及workerman/webman等框架组件具体版本

windows 11
brick/math 0.12.1 Arbitrary-precision arithmetic library
carbonphp/carbon-doctrine-types 3.2.0 Types to use Carbon in Doctrine
doctrine/inflector 2.0.10 PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/...
firebase/php-jwt 6.10.2 A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.
graham-campbell/result-type 1.1.3 An Implementation Of The Result Type
illuminate/bus 11.39.1 The Illuminate Bus package.
illuminate/collections 11.39.1 The Illuminate Collections package.
illuminate/conditionable 11.39.1 The Illuminate Conditionable package.
illuminate/container 11.39.1 The Illuminate Container package.
illuminate/contracts 11.39.1 The Illuminate Contracts package.
illuminate/database 11.39.1 The Illuminate Database package.
illuminate/events 11.39.1 The Illuminate Events package.
illuminate/macroable 11.39.1 The Illuminate Macroable package.
illuminate/pagination 11.39.1 The Illuminate Pagination package.
illuminate/pipeline 11.39.1 The Illuminate Pipeline package.
illuminate/support 11.39.1 The Illuminate Support package.
laravel/serializable-closure 2.0.1 Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.
monolog/monolog 2.10.0 Sends your logs to files, sockets, inboxes, databases and various web services
myclabs/deep-copy 1.12.1 Create deep copies (clones) of your objects
nesbot/carbon 3.8.4 An API extension for DateTime that supports 281 different languages.
nikic/fast-route 1.3.0 Fast request router for PHP
nikic/php-parser 5.4.0 A PHP parser written in PHP
phar-io/manifest 2.0.4 Component for reading phar.io manifest information from a PHP Archive (PHAR)
phar-io/version 3.2.1 Library for handling version information and constraints
phpoption/phpoption 1.9.3 Option Type for PHP
phpunit/php-code-coverage 11.0.8 Library that provides collection, processing, and rendering functionality for PHP code coverage infor...
phpunit/php-file-iterator 5.1.0 FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-invoker 5.0.1 Invoke callables with a timeout
phpunit/php-text-template 4.0.1 Simple template engine.
phpunit/php-timer 7.0.1 Utility class for timing
phpunit/phpunit 11.5.3 The PHP Unit Testing framework.
psr/clock 1.0.0 Common interface for reading the clock.
psr/container 2.0.2 Common Container Interface (PHP FIG PSR-11)
psr/log 3.0.2 Common interface for logging libraries
psr/simple-cache 3.0.0 Common interfaces for simple caching
sebastian/cli-parser 3.0.2 Library for parsing CLI options
sebastian/code-unit 3.0.2 Collection of value objects that represent the PHP code units
sebastian/code-unit-reverse-lookup 4.0.1 Looks up which function or method a line of code belongs to
sebastian/comparator 6.3.0 Provides the functionality to compare PHP values for equality
sebastian/complexity 4.0.1 Library for calculating the complexity of PHP code units
sebastian/diff 6.0.2 Diff implementation
sebastian/environment 7.2.0 Provides functionality to handle HHVM/PHP environments
sebastian/exporter 6.3.0 Provides the functionality to export PHP variables for visualization
sebastian/global-state 7.0.2 Snapshotting of global state
sebastian/lines-of-code 3.0.1 Library for counting the lines of code in PHP source code
sebastian/object-enumerator 6.0.1 Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector 4.0.1 Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context 6.0.2 Provides functionality to recursively process PHP variables
sebastian/type 5.1.0 Collection of value objects that represent the types of the PHP type system
sebastian/version 5.0.2 Library that helps with managing the version number of Git-hosted PHP projects
staabm/side-effects-detector 1.0.5 A static analysis tool to detect side effects in PHP code
symfony/clock 7.2.0 Decouples applications from the system clock
symfony/deprecation-contracts 3.5.1 A generic function and convention to trigger deprecation notices
symfony/polyfill-ctype 1.31.0 Symfony polyfill for ctype functions
symfony/polyfill-mbstring 1.31.0 Symfony polyfill for the Mbstring extension
symfony/polyfill-php80 1.31.0 Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/polyfill-php83 1.31.0 Symfony polyfill backporting some PHP 8.3+ features to lower PHP versions
symfony/translation 7.2.2 Provides tools to internationalize your application
symfony/translation-contracts 3.5.1 Generic abstractions related to translation
symfony/var-dumper 7.2.0 Provides mechanisms for walking through any arbitrary PHP variable
theseer/tokenizer 1.2.3 A small library for converting tokenized PHP source code into XML and potentially other formats
tinywan/exception-handler 1.5.4 webman exception handler plugin
tinywan/jwt 1.10.1 JSON Web Token (JWT) for webman plugin
tinywan/rpc 1.3.0 simple rpc service for webman plugin
tinywan/validate 1.0.2 validate for webman plugin
topthink/think-container 3.0.1 PHP Container & Facade Manager
topthink/think-helper 3.1.10 The ThinkPHP6 Helper Package
topthink/think-validate 3.0.3 think validate
vlucas/phpdotenv 5.6.1 Loads environment variables from .env to getenv(), $_ENV and $_SERVER automagically.
voku/portable-ascii 2.0.3 Portable ASCII library - performance optimized (ascii) string functions for php.
workerman/webman-framework 1.6.14 High performance HTTP Service Framework.
workerman/workerman 5.0.0 An asynchronous event driven PHP framework for easily building fast, scalable network applications.

177 1 1
1个回答

tzbob888

搞清楚了。。。问题就出在variables_order 如果要使用 $_ENV 全局数组,包含了 PHP 启动时加载的环境变量。它的内容取决于 PHP 配置中的 variables_order 设置。

  • 暂无评论
×
🔝