Home > Software engineering >  Can't pass array through function, error: string given
Can't pass array through function, error: string given

Time:10-05

I am trying to send an array via a function, but I only get Uncaught TypeError: Psr\Log\AbstractLogger::error(): Argument #2 ($context) must be of type array, string given, called in.... I'm using KLogger so I can log important stuff on my website and sometimes, putting stuff in an array would be quite useful sometimes.

Here's how everything looks like in my code:

function logger($string, Array $array, $type = 'info') {
    global $filename, $filename_get;    # these variables contains the filename and GET that the visitor are currently at

    $dir = '/destination/somewhere/on-the-server';
    if(!file_exists($dir)) {
        create_folder($dir);    # a function that creates a new folder if it doesn't exists
    }


    $logger = new Katzgrau\KLogger\Logger($dir);

    if($type == 'emergency') {
        $logger->emergency($string.' - '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    } elseif($type == 'alert') {
        $logger->alert($string.' - '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    } elseif($type == 'critical') {
        $logger->critical($string.' - '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    } elseif($type == 'error') {
        $logger->error($string.' - '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    } elseif($type == 'warning') {
        $logger->warning($string.' - '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    } elseif($type == 'notice') {
        $logger->notice($string.' - '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    } elseif($type == 'info') {
        $logger->info($string.' - '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    } elseif($type == 'debug') {
        $logger->debug($string.' '.$filename . ($filename_get == '-' ? null : '?'.$filename_get), (empty($array) ? $array : ''));
    }
}

logger('regular string', [
    'test' => 'hi'
], 'error');

I've tried "everything"! Array $array, &$array, and $array = []. What have I missed? How can I solve this?

CodePudding user response:

You have error in your code. Your second parameter is empty($array) ? $array : ''.

If $array is empty you send the $array, but if it's not empty you send an empty string.

It probably should be like this empty($array) ? [] : $array.

  • Related