1.2.1470. __toString() Throws Exception

Magical method __toString() can’t throw exceptions.

In fact, __toString() may not let an exception pass. If it throw an exception, but must catch it. If an underlying method throws an exception, it must be caught.

A fatal error is displayed, when an exception is not intercepted in the __toString() function.

<?php

class myString {
    private $string = null;

    public function __construct($string) {
        $this->string = $string;
    }

    public function __toString() {
        // Do not throw exceptions in __toString
        if (!is_string($this->string)) {
            throw new Exception("$this->string is not a string!!");
        }

        return $this->string;
    }
}

?>

See also __toString().

1.2.1470.1. Connex PHP features

1.2.1470.1.1. Suggestions

  • Remove any usage of exception from __toString() magic method

1.2.1470.1.2. Specs

Short name

Structures/toStringThrowsException

Rulesets

All, Analyze, Changed Behavior

Exakat since

0.8.4

PHP Version

With PHP 7.4 and older

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Available in

Entreprise Edition, Exakat Cloud