【问题标题】:How to use a PEAR library inside a custom namespace?如何在自定义命名空间中使用 PEAR 库?
【发布时间】:2012-06-03 23:01:37
【问题描述】:

声明自定义命名空间后,我无法使用 PEAR 库。

命名空间和自动加载功能:

<?php
namespace ldapwrangler;
function autoload($class_name)
{
  $path = ROOT_DIR . "/inc/" . str_replace('\\', "/", $class_name) . ".class.php";    
  require_once($path);
}
spl_autoload_register('ldapwrangler\autoload');
?>

如果我尝试这样的 ROOT_DIR/inc/ldapwrangler/LDAP.class.php:

<?php
namespace ldapwrangler;
require_once 'Net/LDAP2.php';

class LDAP{
    protected $connection;
    protected $defaultSearchBase;

    /**
     * @param $conf conf array containing ldap direction login and server.
     */
    function __construct($conf)
    {
        $this->connection = $this->set_connection($conf);
        $this->defaultSearchBase = $conf['basedn'];
    }
    /**
     * Bind to the directory configured in the $conf array
     * 
     * @param $conf conf array containing ldap direction login and server.
     */ 
    function set_connection($conf)
    {
        $ldap = Net_LDAP2::connect($conf);

        // Testing for connection error
        if (PEAR::isError($ldap)) {
            $msg = 'Could not connect to LDAP server: '.$ldap->getMessage();
            Logging::log_message('error',$msg);
            return false;
        }
        return $ldap;
    }

    //rest of the class...
    }
?>

我收到这样的错误:

5 月 29 日 10:03:32 reagand-desktop apache2: PHP 致命错误:require_once(): 无法打开所需的 '/home/reagand/dev/ldap_wrangler/inc/ldapwrangler/Net_LDAP2.class.php' (include_path=' .:/usr/share/php:/usr/share/pear') 在 /home/reagand/dev/ldap_wrangler/config.php 第 18 行

仅供参考,第 18 行是 autoload 函数的 require_once() 部分。

如何告诉 php 不要为 Net_LDAP2 类使用 ldapwrangler 命名空间?或任何其他非 ldapwrangler 类,就此而言。

【问题讨论】:

    标签: php pear autoload netldap spl-autoloader


    【解决方案1】:

    声明您正在使用外部命名空间:

    <?php
    
    namespace ldapwrangler;
    use Net_LDAP2;
    require_once 'Net/LDAP2.php';
    

    声明的namespace 之外的每个类都需要通过use 关键字声明。

    还请查看PSR-0,这是用于命名空间使用等此类事情的标准。

    【讨论】:

    • 我还必须添加 PEAR 和 Net ldap 过滤器:` namespace ldapwrangler;使用 Net_LDAP2;使用 Net_LDAP2_Filter;使用梨; require_once 'Net/LDAP2.php';` 或者,我想我可以在每个 PEAR 或 Net_LDAP2 函数前加上“\”,这样也可以。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2018-07-15
    • 2020-08-12
    • 2016-10-28
    • 2019-06-23
    相关资源
    最近更新 更多