PHP: 面向对象的代码 - Class 'x' 未找到,但有

PHP: Object-oriented code - Class 'x' not found, but there is

我在包含 CryptoGuard 时遇到问题,但也许我在面向对象代码方面存在问题,因为我是这方面的新手。

require_once('CryptoGuard.php'); // = https://github.com/CoreProc/crypto-guard/blob/master/src/CryptoGuard.php

$passphrase = 'my_private_key'; 
$cryptoGuard = new CryptoGuard($passphrase);
$stringToEncrypt = "private string";
$encryptedText = $cryptoGuard->encrypt($stringToEncrypt);
echo $encryptedText;

CryptoGuard 的简单使用示例:https://github.com/CoreProc/crypto-guard(和我用的一样,但我不使用 Composer,所以我只是复制 CryptoGuard.php)。

没有 php 错误,但带有 cryptoGuard 的部分损坏了页面(停止加载更多内容,那里没有 $encryptedText 回显)。

你的问题是Namespace。 CryptoGuard 使用 Coreproc\CryptoGuard;

所以你的代码应该是

require_once('CryptoGuard.php'); // = https://github.com/CoreProc/crypto-guard/blob/master/src/CryptoGuard.php

$passphrase = 'my_private_key';

//Not missing the Namespace here
$cryptoGuard = new \Coreproc\CryptoGuard\CryptoGuard($passphrase);
$stringToEncrypt = "private string";
$encryptedText = $cryptoGuard->encrypt($stringToEncrypt);
echo $encryptedText;

或者,如果您在脚本开头编写,您提供的代码将起作用:

use \Coreproc\CryptoGuard\CryptoGuard;