【问题标题】:PHP: Object-oriented code - Class 'x' not found, but there isPHP:面向对象的代码 - 未找到类“x”,但有
【发布时间】:2015-04-26 08:42:18
【问题描述】:

我在包含 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 回显)。

【问题讨论】:

  • 或者(无论出于何种原因)结果只是空的。您可以尝试echo '>' . $encryptedText . '<'; 来确定该语句是否被执行吗?
  • 您好,MBAas,感谢您的回复。不,页面冻结,不再加载任何内容。我测试过,它只加载“$cryptoGuard = new CryptoGuard($passphrase);”之前的内容,之后什么都没有。
  • 什么是var_dump($cryptoGuard->encrypt($stringToEncrypt));?并且错误报告设置为error_reporting(E_ALL);
  • 您好克里斯蒂安,感谢您的回复。我设置了 error_reporting(E_ALL);我看到了错误:致命错误:在第 44 行的 code.php 中找不到类 'CryptoGuard' (= $cryptoGuard = new CryptoGuard($passphrase);)。所以看起来我认为面向对象的代码存在问题,但真的不知道如何解决这个问题,因为 require_once 有效。
  • 为了确定 CryptoGuard.php 是否正确加载,我在 CryptoGuard.php 文件的末尾添加了echo "loaded";,它确实加载正确。很奇怪,请问哪里有问题?

标签: php oop object namespaces


【解决方案1】:

您的问题是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;

【讨论】:

  • 非常感谢。我第一次实现了面向对象的代码,所以我不知道“命名空间”是做什么的。 :)
  • 没问题 :) 每个人都从某事开始。很高兴我能帮上忙。命名空间和 OOP 非常强大,你应该更经常地用它做一些事情。借助 PHPStrom 等优秀的 IDE,它们可以让您的开发速度更快。
猜你喜欢
  • 2020-06-12
  • 1970-01-01
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多