【发布时间】:2013-01-13 00:54:13
【问题描述】:
我创建了一个 CI 模型,它根据传入的参数动态加载某些类。这些类只是 phpseclib 周围的包装类,用于与不同设备建立 ssh 连接。 我注意到的是,当我尝试执行一种特定方法时,我收到了上述错误消息。
这里有一些示例代码可以帮助您了解我在做什么。这是我的模型的样子:
public function get_portstatusall($ip, $switchname)
{
$classname = $this->switchToClassName($switchname);
try{
include_once(APPPATH.'libraries/'.$classname.'.php');
$switch_obj = new $classname($ip, 'password', '');
$switch_obj->connect();
$data = $switch_obj->dosomething();
$switch_obj->disconnect();
return $data;
}
catch (Exception $e) {
echo 'this really should be logged...';
return false;
}
}
public function get_portstatusindividual($ip, $switchname)
{
$classname = $this->switchToClassName($switchname);
try{
include_once(APPPATH.'libraries/'.$classname.'.php');
$switch_obj = new $classname($ip, 'password', '');
$switch_obj->connect();
$data = $switch_obj->dosomethingelse();
$switch_obj->disconnect();
return $data;
}
catch (Exception $e) {
echo 'this really should be logged...';
return false;
}
}
如您所见,我正在根据传入的开关名称动态确定要加载的类。这段代码成功地加载了一个名为“device123.php”的类,比方说。依次类 device123 实例化 phpseclib 附带的 SSH2 对象,并使用它向设备发送 ssh 命令。
这是来自设备 123 的一段代码:
class device123
{
// sample code to demo how to use phpseclib to create an interactive ssh session.
//this library relies on phpseclib. you must include this class and SSH2.php from Net/phpseclib.
private $_hostname;
private $_password;
private $_username;
private $_connection;
private $_data;
private $_timeout;
private $_prompt;
public function __construct($hostname, $password, $username = "", $timeout = 10)
//public function __construct($params)
{
echo 'in the switch constructor<br>';
set_include_path(get_include_path() . PATH_SEPARATOR . '/var/www/phpseclib');
include('Net/SSH2.php');
$this->_hostname = $hostname;
$this->_password = $password;
$this->_username = $username;
} // __construct
public function connect()
{
$ssh = new Net_SSH2($this->_hostname);
if (!$ssh->login($this->_username, $this->_password)) { //if you can't log on...
die("Error: Authentication Failed for $this->_hostname\n");
}
else {
$output= $ssh->write("\n"); //press any key to continue prompt;
$prompt=$ssh->read('/([0-9A-Z\-])*(#)(\s*)/i', NET_SSH2_READ_REGEX);
if (!$prompt) {
die("Error: Problem connecting for $this->_hostname\n");
}
else {
$this->_connection = $ssh;
}
}
} // connect
public function close()
{
$this->_send('exit');
} // close
public function disconnect()
{
$this->_connection->disconnect();
$ssh=NULL;
}
我认为我不太明白如何重新声明 SSH2 类...但我想看看我是否没有正确地销毁/清理自己。 为了帮助排除故障,我尝试在 SSH2 类以及名为 device123 的包装类的构造函数和析构函数中添加调试回显语句。 一切看起来都不错……
我不认为我在正确的轨道上......你能告诉我你认为我应该从哪里开始寻找吗? 是因为有可能这两种方法都被调用......一个接一个......并且两者都可能加载同一个类?
谢谢。
【问题讨论】:
-
你能不能也发帖
device123.php.. -
使用 PHP 内置的自动加载功能可以实现类的动态加载。无需在这里重新发明轮子。见php.net/manual/en/function.spl-autoload-register.php
-
@Spudley。嘿,谢谢你的提示!我不知道这件事。现在我已经修复了这个错误......我将花一些时间使用这个 spl_autoload 东西重新实现代码。再次感谢。
标签: php codeigniter phpseclib