最近在 学习设计模式,初学 有些不理解的地方!
class MysqlConfiguration
{
private $host;
private $port;
private $username;
private $password;
private $db_name;
public function __construct(string $host, int $port, string $username, string $password,string $db_name)
{
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->db_name = $db_name;
}
public function getHost(): string
{
return $this->host;
}
public function getPort(): int
{
return $this->port;
}
public function getUsername(): string
{
return $this->username;
}
public function getPassword(): string
{
return $this->password;
}
public function getDbName(): string
{
return $this->db_name;
}
}
class Mysql
{
private $configuration;
public function __construct(DatabaseConfiguration $config)
{
$this->configuration = $config;
}
public function connect(){
return mysqli_connect($this->configuration->getHost(),$this->configuration->getUsername() ,$this->configuration->getPassword,$this->configuration->getDbName(),$this->configuration->getPort());
}
}
如上是一个数据库连接类 将数据库的配置 单独拿出来 写一个类文件 将公共不变的部分 写成另一个类, 这样当数据库连接的参数发生变化 可以直接切换另一个类就可以了…
有一个问题: 上面的构造方法中 为什么一定要强制传 对象参数 这个参数的目的是将配置内容复制给成员变量, 那用array 形式不也是可以 赋值的嘛 不是很理解这个问题! 希望大佬们给指点一下!