带有SessionHandlerInterface的PHP错误命名空间


PHP error namespace with SessionHandlerInterface

我有一个PHP代码的问题,我想解决:

<?php    
namespace MyNamespace;
class MySessionHandler implements SessionHandlerInterface
{
    public function open($a, $b)
    {
    }
    public function close()
    {
    }
    public function read($sid)
    {
    }        
    public function write($sid, $data)
    {
    }        
    public function destroy($sid)
    {
    }
    public function gc($expire)
    {
    }
}
// ####################### error! ######################
$a = new MySessionHandler();
?>

当我运行代码时,它输出如下错误:
Fatal error: Interface 'MyNamespace'SessionHandlerInterface' not found in /var/www/html/2.php on line 5

(我有PHP 5.5.9-1ubuntu4)
我不知道它有什么问题。

您已经为代码设置了名称空间,因此php正在您的自定义名称空间范围内查找SessionHandlerInterface。基本上,您需要告诉php在全局/根空间中查找接口:

namespace MyNamespace;
class MySessionHandler extends 'SessionHandlerInterface {
    // your implementation
}

由于定义了命名空间,所以这个类没有显示出来。

这就是为什么你会得到错误:

Fatal error: Interface 'MyNamespace'SessionHandlerInterface' not found

你有两种可能。

方法1。use所需的名称空间


下的命名空间,你可以只写这行:

use SessionHandlerInterface;

一切都会好起来的。

你现在可以像往常一样实现这个接口了。

<?php    
namespace MyNamespace;
use SessionHandlerInterface;
class MySessionHandler implements SessionHandlerInterface
{
    public function open($a, $b)
    {
    }
    public function close()
    {
    }
    public function read($sid)
    {
    }        
    public function write($sid, $data)
    {
    }        
    public function destroy($sid)
    {
    }
    public function gc($expire)
    {
    }
}
$a = new MySessionHandler();
?>

方法2。implementextend "'SessionHandlerInterface"


您可以implementextend SessionHandlerInterface,在实现扩展关键字后加上反斜杠,如下所示:

'SessionHandlerInterface

否则,PHP解析器将在您的命名空间中搜索SessionHandlerInterface类,如果您没有使用 SessionHandlerInterface命名空间(如方法1),则会发生致命错误

<?php    
namespace MyNamespace;
class MySessionHandler implements 'SessionHandlerInterface
{
    public function open($a, $b)
    {
    }
    public function close()
    {
    }
    public function read($sid)
    {
    }        
    public function write($sid, $data)
    {
    }        
    public function destroy($sid)
    {
    }
    public function gc($expire)
    {
    }
}
$a = new MySessionHandler();
?>