[英]PHP - using a namespace in another namespace
I'm trying to use some files from another namespace inside one of my own namespaces, however it's not recognising the exceptions from the Defuse\\Crypto
namespace. 我试图使用我自己的名称空间中另一个名称空间中的某些文件,但是它无法识别Defuse\\Crypto
名称空间中的异常。
I've checked all the files, and everything is there stored perfectly in my directory. 我检查了所有文件,所有内容都完美存储在我的目录中。 I can include the autoloader with no exceptions too. 我也可以毫无例外地包括自动装带器。
What can I do to cleanly use both namespaces in the same file? 如何在同一文件中完全使用两个名称空间?
Here's my code: 这是我的代码:
namespace Defuse\Crypto;
$path = '/my/path/to/DefuseCrypto/autoloader';
require_once $path;
use \Defuse\Crypto\Crypto;
use \Defuse\Crypto\Exception as Ex;
namespace myNamespace;
class myClass
{
static function encrypt_key($key)
{
try
{
$ciphertext = Crypto::encrypt($key, $privateKey);
return $ciphertext;
}
catch (Ex\CryptoTestFailedException $ex)
{
return false;
}
catch (Ex\CannotPerformOperationException $ex)
{
return false;
}
}
static function decrypt_key($key)
{
try
{
$decryptedKey = Crypto::decrypt($key, $privateKey);
return $decryptedKey;
}
catch (Ex\InvalidCiphertextException $ex)
{
return false;
}
catch (Ex\CryptoTestFailedException $ex)
{
return false;
}
catch (Ex\CannotPerformOperationException $ex)
{
return false;
}
}
}
Of course you can use namespaces in classes. 当然,您可以在类中使用名称空间。 But you start from root with leading \\ 但是,您从根本开始以\\
Try this: 尝试这个:
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Exception as Ex;
After namespaces are included, you can use them. 包括名称空间后,即可使用它们。 If you want to use a namespace often (more than 1 time), include namespaces in the top. 如果要经常使用命名空间(超过1次),请在顶部包含命名空间。 Otherwise, you can use the full path at the place where you need. 否则,您可以在需要的地方使用完整路径。
Further, for maintainbility reasons use max. 此外,出于可维护性原因,请使用max。 1 namespace line. 1个名称空间行。
Change your first line in: 更改第一行:
namespace myNamespace;
And remove the second namespace line! 并删除第二个名称空间行!
Three options: either you specify the fully qualified (so absolute) namespace directly: 三个选项:您可以直接指定完全限定(绝对)的名称空间:
catch (\Defuse\Crypto\Exception\CryptoTestFailedException $ex)
Or you use a relative namespace inside the currently active namespace: 或者,您可以在当前活动的名称空间中使用相对名称空间:
catch (Exception\CryptoTestFailedException $ex)
Or you have to declare the namespace under an alias for internal usage just as @HenriS. 或者,您必须在别名下声明名称空间以供内部使用,就像@HenriS一样。 suggested above: 以上建议:
use Defuse\Crypto\Exception as Ex;
[...]
catch (Ex\CryptoTestFailedException $ex)
In general nothing speaks against using multiple namespaces in one file, that is common. 通常,没有什么可以反对在一个文件中使用多个名称空间,这很常见。 But I agree with @HenriS. 但是我同意@HenriS。 here that it is not a good practice to create a separate namespace for exceptions. 在这里,为例外创建单独的命名空间不是一个好习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.