如何在 PHP 中从外部所需文件访问常量


How do I access constants from a external required file in PHP?

如果我将常量保留在类代码中,我制作的这个类就可以工作,但我想从用户可以注释或取消注释掉 c 常量值的外部文件访问它们。

它以这种方式工作得很好,但我不希望用户在代码中翻找:

class passwordStringHandler
{
# const PWDALGO = 'md5';
# const PWDALGO = 'sha1';
# const PWDALGO = 'sha256';
# const PWDALGO = 'sha512';
const PWDALGO = 'whirlpool';
  /* THIS METHOD WILL CREATE THE SALTED USER PASSWORD HASH DEPENDING ON WHATS BEEN
    DEFINED    */
function createUsersPassword()
{
$userspassword = 'Te$t1234';
$saltedpassword='';    
if ((defined('self::PWDALGO')) && (self::PWDALGO === 'md5'))
{
    $saltedpassword = md5($userspassword . $this->pwdsalt);
    echo("The salted md5 generated hash is: " . $saltedpassword . "<br>");
    return $saltedpassword;
}elseif ((defined('self::PWDALGO')) && (self::PWDALGO === 'sha1')){
    $saltedpassword = sha1($userspassword . $this->pwdsalt);
    echo("The salted sha1 generated hash is: " . $saltedpassword . "<br>");
    return $saltedpassword;
}elseif ((defined('self::PWDALGO')) && (self::PWDALGO === 'sha256')){
    $saltedpassword = hash('sha256', $userspassword . $this->pwdsalt);
    echo("The salted sha256 generated hash is: " . $saltedpassword . "<br>");
    return $saltedpassword;
}elseif ((defined('self::PWDALGO')) && (self::PWDALGO === 'sha512')){
    $saltedpassword = hash('sha512', $userspassword . $this->pwdsalt);
    echo("The salted sha512 generated hash is: " . $saltedpassword . "<br>");
    return $saltedpassword;
}elseif ((defined('self::PWDALGO')) && (self::PWDALGO === 'whirlpool')){
    $saltedpassword = hash('whirlpool', $userspassword . $this->pwdsalt);
    echo("The salted whirlpool generated hash is: " . $saltedpassword . "<br>");
    return $saltedpassword;
}
else
    echo("No password algro is defined! Edit the [<strong>PWDALGO</strong>] options in the <strong>systemConfiguration.php</strong><br>");  
    return false;
}

这工作正常,因为它被硬编码到类文件中:

我希望它使用它工作:

require ("../configs/systemConfiguration.php");   
class passwordStringHandler
{

我一直在我的 if/else 语句中得到 else 它找不到是否定义了 PWDALGO。

或者这样

class passwordStringHandler
{
require ("../configs/systemConfiguration.php");

我不知道这是否可能,因为我不断收到错误,我认为您不能在类范围内包含或要求文件。

将来,如果我让它工作,我想要一个安装脚本来检查服务器以查看可用的加密类型,并列出供用户选择首选的加密方法,然后自动为他们设置。 并能够稍后从管理员控制面板更改加密方法。

听起来您希望这些常量跨越对象(类(,而不是仅限于passwordStringHandler类。

如果是这样的话,我建议你选择define()而不是const

喜欢这个:

系统配置.php

define('PWDALGO', 'whirlpool');

密码字符串处理程序.php

require ("../configs/systemConfiguration.php");
class passwordStringHandler
{
    if ((defined('PWDALGO')) && (PWDALGO === 'md5'))

更多信息在这里:define(( vs const