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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: travis dot detert at gmail dot com
New email:
PHP Version: OS:

 

 [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

Add a Patch

Pull Requests

Add a Pull Request

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: Thu Mar 28 13:01:28 2024 UTC