search
HomeBackend DevelopmentPHP7PHP 7.4 allows throwing exceptions from __toString()

PHP 7.4 allows Exceptions from __toString()

Introduction

Currently prohibited from __toString() throws an exception and will cause a fatal error. This makes calling arbitrary code dangerous and makes it a problematic general-purpose API. This RFC aims to remove this restriction.

The rationale for the current behavior is that string conversions are performed in many places throughout the engine and standard library, and not everywhere are prepared to handle exceptions "correctly", i.e. as early as possible.

From a technical perspective, this restriction is ultimately ineffective, since exceptions during string conversion can still be triggered by error handlers that convert recoverable errors into exceptions:

set_error_handler(function() {
    throw new Exception();
});
 
try {
    (string) new stdClass;
} catch (Exception $e) {
    echo "(string) threw an exception...\n";
}

In fact, Symfony exploits this vulnerability to bypass the current restrictions. Unfortunately, this relies on the $errcontext parameter, which disappeared in PHP 8.

However, until we do a full review of string conversion in this code base, past articles on this topic There has been no discussion of loosening this restriction. This has been done in an attached implementation request.

Recommendations

Allow exceptions to be thrown from __toString() and it will behave as usual. Fatal errors are no longer triggered.

Also, convert the "cannot be converted to a string" and "__toString() must return a string value" recoverable fatal errors into correct error exceptions, consistent with the error policy established in PHP 7 .

Extension Guidelines

Extension authors who want to gracefully handle exceptions from string conversions should consider the following guidelines:

● If zval_get_string( ), convert_to_string() and friends generate an exception, they still generate a string. This string is guaranteed to be temporary. This means there is no need to free it, but it is possible to do so. In context, you can choose the more convenient option.

● If the conversion from object to string fails, the result of the string conversion will be an empty string, or if the array is converted to a string and the error handler raises the result notification to an exception. "Array". (The behavior is the same as before.)

● Usually it is enough to check whether an exception was thrown using the usual if (EG(exception)) check:

zend_string *str = zval_get_string(val);
if (EG(exception)) {
    // Possibly free other resources here.
    return;
}

Except In addition, some helper APIs are provided that model conversions as error-prone operations:

// Like zval_get_string() but returns NULL on conversion failure.
zend_string *str = zval_try_get_string(val);
if (!str) {
    // Possibly free other resources here.
    return;
}
// Main code.
zend_string_release(str);
 
 
// Like zval_get_tmp_string() but returns NULL on conversion failure.
zend_string *tmp, *str = zval_try_get_tmp_string(val, &tmp);
if (!str) {
    // Possibly free other resources here.
    return;
}
// Main code.
zend_tmp_string_release(tmp);
 
 
// Like convert_to_string() but returns a boolean indicating conversion success/failure.
if (!try_convert_to_string(val)) {
    // Possibly free other resources here.
    return;
}
// Main code.

try_convert_to_string() will not modify the original value if the conversion fails. Therefore, using it is safer than using convert_to_string() and exception checking.

While checking every string conversion will certainly put you on the safe side, ignoring these checks usually just results in a few unnecessary calculations and possibly redundant warnings. The main thing you should be aware of are operations that modify persistent structures (such as databases).

Backward-incompatible changes

The transition from a recoverable fatal error to an error exception is technically a BC break.

Translation: https://wiki.php.net/rfc/tostring_exceptions

The above is the detailed content of PHP 7.4 allows throwing exceptions from __toString(). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Which versions of PHP7 have introduced new operatorsWhich versions of PHP7 have introduced new operatorsMar 03, 2025 pm 04:37 PM

This article details PHP 7's new operators: the null coalescing (??), spaceship (<=>), and null coalescing assignment (??=) operators. These enhance code readability and performance by simplifying null checks and comparisons, indirectl

How to optimize PHP7 code to improve performanceHow to optimize PHP7 code to improve performanceMar 03, 2025 pm 04:28 PM

This article examines optimizing PHP7 code for performance. It addresses common bottlenecks like inefficient database queries, I/O operations, and memory leaks. Solutions include efficient coding practices, database & caching strategies, asynch

What are the impacts of different versions of PHP7 on memory consumptionWhat are the impacts of different versions of PHP7 on memory consumptionMar 03, 2025 pm 04:35 PM

PHP 7's minor version differences yield subtle memory consumption variations. While newer versions generally improve performance and memory efficiency via Zend Engine and garbage collection optimizations, the impact is application-dependent. Signif

How to Use Sessions Effectively in PHP 7?How to Use Sessions Effectively in PHP 7?Mar 10, 2025 pm 06:20 PM

This article details effective PHP 7 session management, covering core functionalities like session_start(), $_SESSION, session_destroy(), and secure cookie handling. It emphasizes security best practices including HTTPS, session ID regeneration, s

How to Upgrade from PHP 5.6 to PHP 7?How to Upgrade from PHP 5.6 to PHP 7?Mar 10, 2025 pm 06:29 PM

This article details upgrading PHP 5.6 to PHP 7, emphasizing crucial steps like backing up, checking server compatibility, and choosing an upgrade method (package manager, compiling, control panel, or web server configuration). It addresses potentia

What impact does the PHP7 version update have on session processing?What impact does the PHP7 version update have on session processing?Mar 03, 2025 pm 04:31 PM

This article examines session handling in PHP7, highlighting performance improvements stemming from the enhanced Zend Engine. It discusses potential compatibility issues from upgrading and details optimization strategies for security and scalability

What bugs have been fixed in the PHP7 version updateWhat bugs have been fixed in the PHP7 version updateMar 03, 2025 pm 04:36 PM

PHP 7 significantly improved upon previous versions by addressing numerous bugs, enhancing performance, and bolstering security. Key improvements included a rewritten Zend Engine 3, optimized memory management, and refined error handling. While gene

How to Monitor PHP 7 Performance with Tools like New Relic?How to Monitor PHP 7 Performance with Tools like New Relic?Mar 10, 2025 pm 06:28 PM

This article explains how to monitor PHP 7 application performance using New Relic. It details New Relic's setup, key performance indicators (KPIs) like Apdex score and response time, bottleneck identification via transaction traces and error track

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!