search

Home  >  Q&A  >  body text

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?

<?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?)

淡淡烟草味淡淡烟草味2744 days ago953

reply all(3)I'll reply

  • 世界只因有你

    世界只因有你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/...

    reply
    0
  • 漂亮男人

    漂亮男人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}");
            }
        }
    }

    reply
    0
  • 代言

    代言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.

    reply
    0
  • Cancelreply