php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #72382 THIS SHOULD BE CONSIDERED A BUG: __toString() must not throw an exception
Submitted: 2016-06-11 04:27 UTC Modified: 2016-06-11 04:37 UTC
From: travis dot detert at gmail dot com Assigned:
Status: Duplicate Package: Class/Object related
PHP Version: Irrelevant OS: All OS
Private report: No CVE-ID: None
 [2016-06-11 04:27 UTC] travis dot detert at gmail dot com
Description:
------------
The fundamental behavior of "__toString() must not throw an exception" needs to be changed.  This problem is completely antithetical to object oriented design, and just doesn't even make sense.

class Template{
function __construct($path){
$this->path = $path;
}

function __toString(){
if(!file_exists($this->path)){
throw new Exception('Path does not exist');
}else{
//process template
}
}

$Template = new Template('/path/does/not/exist.php');
echo (string)$Template;

There is absolutely no sane reason that this should be a fatal php error.

Test script:
---------------
class Template{
function __construct($path){
$this->path = $path;
}

function __toString(){
if(!file_exists($this->path)){
throw new Exception('Path does not exist');
}else{
//process template
}
}

$Template = new Template('/path/does/not/exist.php');
echo (string)$Template;


Expected result:
----------------
Raise a regular exception.  Why would raising an exception ever be not allowed?  What is the point?

Actual result:
--------------
__toString() must not throw an exception

Pretty much the worst result possible.  Unrecoverable fatal error.  Why?  What is the point?

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-06-11 04:37 UTC] requinix@php.net
-Status: Open +Status: Duplicate -Package: PHP Language Specification +Package: Class/Object related
 [2016-06-11 04:37 UTC] requinix@php.net
Duplicate of request #53648.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Nov 22 15:01:32 2024 UTC