【发布时间】:2014-10-01 00:40:45
【问题描述】:
我从未在 PHP 中使用过接口或抽象类,但我想支持相同对象的相似但不同类型的对象(在本例中为网络交换机),并可能在未来添加更多。我通过 SSH (PHPSecLib) 与他们通信,交互方式不同,实际方法相同。
在我的特殊情况下,我相信一个抽象类,实现常量、私有变量、连接函数和构造函数/析构函数是合适的,只留下扩展类来实现功能,其中接口只是一个模板,但每个扩展类仍然会重新实现它们之间相同的方法。
我认为抽象类是在这种情况下要走的路是正确的吗?是否需要将空方法放置在被扩展类覆盖的抽象类中,或者扩展类是否可以包含抽象类中不存在的方法?
例子:
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/devicepo/public_html/include/PHPSecLib');
include('Net/SSH2.php');
include('File/ANSI.php');
abstract class Switch
{
const STATUS_UNKNOWN = "-1";
const STATUS_OFFLINE = "0";
const STATUS_ONLINE = "1";
public $conn;
private $_server;
private $_username;
private $_password;
private $_bashshell;
public function __construct($server, $username, $password)
{
if (!$server)
die("Switch configuration not Defined");
$this->_server = $server;
$this->_username = $username;
$this->_password = $password;
}
public function connect()
{
// Establish new SSH2 Connection
$this->conn = new Net_SSH2($this->_server, 22);
if(!$this->conn->login($this->_username, $this->_password))
{
die("Failed to connect to Switch: " . $this->_server);
}
}
public function enable_port($port)
{
// Define in extended classes
}
public function disable_port($port)
{
// Define in extended classes
}
}
?>
【问题讨论】:
标签: php oop interface abstract-class phpseclib