使用SessionHandlerInterface的PHP错误命名空间

时间:2014-08-17 14:16:13

标签: php class

我对这个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
我不知道它的问题是什么。

2 个答案:

答案 0 :(得分:1)

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

namespace MyNamespace;

class MySessionHandler extends \SessionHandlerInterface {
    // your implementation
}

答案 1 :(得分:1)

此类界面不会显示,因为您定义了命名空间

这就是您收到错误的原因:

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&#34; \ SessionHandlerInterface&#34;


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