How to limit method parameters in php? The parameter is an array. How to specify the number and key names of the passed array elements?
淡淡烟草味
淡淡烟草味 2017-06-14 10:49:58
0
3
919
<?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?)

淡淡烟草味
淡淡烟草味

reply all(3)
世界只因有你

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/...

漂亮男人

function connect(array $config) {
    $requiredColumns = ['host','port','database','username','password'];
    foreach($requiredColumns as $column) {
        if(!isset($config[$column])) {
            throw new Exception("缺少参数{$column}");
        }
    }
}
代言

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template