Php Error Handling In Constructor
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might
Php Constructor Return
have Meta Discuss the workings and policies of this site About php throw exception Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up How to treat exceptions in constructor best? up vote 2 down vote favorite 2 How to treat exception in best way in construct? option1 - catch exception where object created: class Account { function __construct($id){ if(empty($id)){ throw new My_Exception('id can\'t be empty'); } // ... } } class a1 { function just($id){ try { $account = new Account($id); } catch(Exception $e){ $e->getMessage(); } } class a2{ function just($id){ try { $account = new Account($id); } catch(Exception $e){ $e->getMessage(); } } option2: catch exception inside __construct class Account{ function __construct($id){ try{ if(empty($id)){ throw new My_Exception('id can\'t be empty'); } // ... } catch(My_Exception $e) { } } Please write in which cases should be used option1 and in which should be used option2 or other better solution. Thanks php exception exception-handling share|improve this question edited Feb 17 '14 at 2:11 Darren Cook 11.4k446106 asked Sep 5 '10 at 13:13 Yosef 7,1721487145 1 I'm not voting to close because I'm not sure I all the details of your specific question but here is a very closely related one: stackoverflow.com/questions/2685857/php-exceptions-in-classes (I personally like the alternative method @Gordon presents in his answer using ::create() best) –Pekka 웃 Sep 5 '10 at 13:16 thank great link! &ndash
and Objects Namespaces Errors Exceptions Generators References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting Using Register Globals User Submitted Data Magic Quotes Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Dealing with XForms Handling file uploads Using remote files Connection handling Persistent Database Connections Safe Mode Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line http://stackoverflow.com/questions/3646157/how-to-treat-exceptions-in-constructor-best Specific Extensions Compression and Archive Extensions Credit Card Processing Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services http://php.net/manual/en/exception.construct.php Windows Only Extensions XML Manipulation Keyboard Shortcuts? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search(current page) / Focus search box Exception::getMessage » « Exception PHP Manual Language Reference Predefined Exceptions Exception Change language: English Brazilian Portuguese Chinese (Simplified) French German Japanese Korean Romanian Russian Spanish Turkish Other Edit Report a Bug Exception::__construct (PHP 5 >= 5.1.0, PHP 7)Exception::__construct — Construct the exception Description public Exception::__construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] ) Constructs the Exception. Parameters message The Exception message to throw. code The Exception code. previous The previous exception used for the exception chaining. Note: Calling the constructor of class Exception from a subclass ignores the default arguments, if the properties $code and $message are already set. Changelog Version Description 7.0.0 The previous parameter is now of type Throwable. 5.3.0 The previous parameter was added. Notes Note: The message is NOT binary safe.
add a note User Contributed Notes 3the object is created $validPlace = new geoLocation(-34.1232, 116.3422); // invalid coordinates, the object is NOT created $invalidPlace = new geoLocation(999, 999); I can't https://www.sitepoint.com/community/t/can-a-constructor-fail/4322 just return FALSE, because constructors don't allow return values. I'm aware that validation http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3 should be done with a special validating class, but I'm curious as to whether what I want to do is possible. disgracian 2008-10-10 04:38:18 UTC #2 The standard way in Java and other languages is to throw some kind of exception, which in turn has to be caught and handled by the php error code that attempts to create the object. I don't know enough about PHP OO, but I can give you a basic example in Java: public class SomeClass { private String _data; public SomeClass(String param) { if(param.length() == 0) throw new IllegalArgumentException("Param too short!"); else _data = param; } } In the calling code: try { SomeClass bob = new SomeClass(""); } catch(IllegalArgumentException ex) { System.err.println(ex.message()); } php error handling My syntax is probably a bit sloppy but that's the general idea. Cheers,D. disgracian 2008-10-10 04:53:36 UTC #3 Alternatively, if the values passed to the constructor are invalid, you could set a publicly-accessible property that flags it as invalid, and leave it uninitialised. Cheers,D. fattyjules 2008-10-11 03:16:39 UTC #4 Could anyone supply a PHP way to do with try/throw/catch? oddz 2008-10-11 04:09:09 UTC #5 Solution for killing the object: http://bugs.php.net/bug.php?id=9253&edit=1 fattyjules 2008-10-11 04:52:48 UTC #6 Thanks everyone, but it's beginning to look like what I want isn't possible. I can't unset($this) within the class, http://au2.php.net/manual/en/function.unset.php says 'Note: It is not possible to unset $this inside an object method since PHP 5.' I can't set $this to NULL or FALSE, http://bugs.php.net/bug.php?id=27659 says 'Actually this is expected behavior. We explicitly decided to have $thisbeing readonly because of internal problems with the new engine.' Perhaps I need to look at factory? logic_earth 2008-10-11 05:23:53 UTC #7
not until developers have had that chance that some agreed-upon good usage and bad usage cases start to emerge. Once they do emerge, we can finally start to classify them as best or worst practices. Exception handling in PHP is not a new feature by any stretch. In this article, we'll discuss two new features in PHP 5.3 based around exceptions. The first is nested exceptions and the second is a new set of exception types offered by the SPL extension (which is now a core extension of the PHP runtime). Both of these new features have found their way into the book of best best practices and deserve to be examined in detail. Special note: some of these features have existed in PHP < 5.3 or are at least capable of being implemented in PHP < 5.3. When this article mentions PHP 5.3, it is not in the strictest sense of the PHP runtime. Instead, it is meant that code bases and projects that are adopting PHP 5.3 as a minimum version but also all of the best practices that have emerged in this new phase of development. This phase of development highlighted by the "2.0" efforts of projects like Zend Framework, Symfony, Doctrine and PEAR to name a select few. Background Previously in PHP 5.2, there was a single exception class Exception. Generally, speaking from a Zend Framework / PEAR coding standard perspective, this exception class became the root for all exceptions that might be thrown from within your library. For example, if you created a library for your company MyCompany, then you would, according to ZF/PEAR standards, have prefixed all code with MyCompany_. For this library, you might create a base exception for your library code: MyCompany_Exception, which extends the PHP class Exception and from which all your components might inherit, subclass, and throw. So, if you created a component MyCompany_Foo, it might have a base exception class called MyCompany_Foo_Exception that is expected to be thrown from within the MyCompany_Foo component. These exceptions can be caught by attempting to catch MyCompany_Foo_Exception, MyCompany_Exception, or simply Exception. This would allow 3 levels of granularity (or more depending on how many times the MyCompany_Foo_Exception was subclassed) to consumers of this component in this particular library, and handle that exception in a way they deem fit. New Feature: Nesting In PHP 5.3,