<?php
class mysql
{
private $con;
private $query;
public function err($error)
{
die('操作错误,错误信息为:' . $error);
}
public function connect(array $config)
{
extract($config);
$this->con = mysqli_connect($dbhost, $dbuser, $dbpsw);
if (!$this->con) {
$this->err(mysqli_connect_error());
}
if (!mysqli_select_db($this->con, $dbname)) {
$this->err(mysqli_error($this->con));
}
mysqli_query($this->con, "set name " . $dbcharset);
}
}
?>
In the connect method, the number of incoming arrays must be 5: keyarray($dbhost,$dbuser,$dbpsw,$dbname,$dbcharset)
I am used to Java's strong typing, but I feel that PHP is not rigorous in many places. Will this increase the amount of code in the method body? (Write judgment in the method body?)
世界只因有你2017-06-14 10:51:58
Define a standard value array, use array_merge
to merge the standard array with the passed parameters, and get the value according to the key name of the standard array when using it.
Reference: https://github.com/top-think/...
漂亮男人2017-06-14 10:51:58
function connect(array $config) {
$requiredColumns = ['host','port','database','username','password'];
foreach($requiredColumns as $column) {
if(!isset($config[$column])) {
throw new Exception("缺少参数{$column}");
}
}
}
代言2017-06-14 10:51:58
You can consider using array_diff
array array_diff ( array $array1 , array $array2 [, array $... ] )
Comparison returns values that are in array1 but not in array2 or any other parameter array.