带有SessionHandlerInterface的PHP错误命名空间

带有SessionHandlerInterface的PHP错误命名空间,php,class,Php,Class,我想解决这个PHP代码的一个问题: <?php namespace MyNamespace; class MySessionHandler implements SessionHandlerInterface { public function open($a, $b) { } public function close() { } public function read($sid) { }

我想解决这个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();
?>

当我运行代码时,它会输出以下错误:
致命错误:在第5行的/var/www/html/2.php中找不到接口“MyNamespace\SessionHandlerInterface”

(我有
PHP5.5.9-1ubuntu4


我不知道它有什么问题

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

namespace MyNamespace;

class MySessionHandler extends \SessionHandlerInterface {
    // your implementation
}

这种类似接口的类不会出现,因为您定义了一个命名空间

这就是为什么会出现错误:

致命错误:未找到接口“MyNamespace\SessionHandlerInterface”

你有两种可能

方法1<代码>使用所需的命名空间
在名称空间下,您可以只写以下行:

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();
?>

如果
SessionHandlerInterface
在全局空间中,则必须在其前面加上反斜杠,
\SessionHandlerInterface
<?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();
?>