I have some code in my opencart php code that is written for php 8.0. It contains a pipe symbol. I have used composer to try and update this but it does not clean up the code. The code is in this file. upload\system\library\log.php line 31.
public function write(string|array $message): void {
$this->message .= date('Y-m-d H:i:s') . ' - ' . print_r($message, true) . "\n";
}
How can I replace this pipe. This is the error that it is throwing.
Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE) in upload\system\library\log.php on line 31
CodePudding user response:
This is called a union type and they were explicitly introduced in PHP 8.0 (RFC).
As documented there the pre-php8 way of doing this was to used doc block formatting:
/**
* @param string|array $message
**/
public function write($message): void {
$this->message .= date('Y-m-d H:i:s') . ' - ' . print_r($message, true) . "\n";
}
The major downside here is this doesn't get type checked by the compiler but, it should be picked up by most IDEs correctly.
CodePudding user response:
If you need to retain the type checking, you can do it manually and throw a TypeError, which is what happens in PHP8 automatically. If it's not critical, I'd just do what @JonathanWommack said.
public function write($message): void {
if(!is_array($message) && !is_string($message))
{
throw new TypeError(sprintf('Argument #1 ($message) must be of type string or array, %s given', gettype($message));
}
$this->message .= date('Y-m-d H:i:s') . ' - ' . print_r($message, true) . "\n";
}