Jump to content

Archived

This topic is now archived and is closed to further replies.

akheron

Abort object instantiation

Recommended Posts

Hi, I've been trying to figure out how to make an object abort it's own instantiation, I've searched all over google and php.net to no avail and could really use a hand. What I need is to be able to check to see if certain conditions are met within the constructor function and if they are not then destroy the object and pass that the object could not be created. Here is some sample code showing exactly what I'm trying to do.
[code]
class myClass
{
    public function __construct($number)
    {
        if(!is_int($number)
        {
            break_fail_commit_suicide_kill_object();
        }
    }
}

$val = 'text';

if( $myObject = new myClass($val) )
{
   echo "this should not print";
}

$val = 5;

if( $myOtherObject = new myClass($val) )
{
   echo "this should print";
}
[/code]

Share this post


Link to post
Share on other sites
If you are checking that in the constructor you can check it in the script that instantiate the class before you instantiate it.

Alternatively you can call the __destructor function to clean up the bits neccessary.

Share this post


Link to post
Share on other sites
Unfortunately what I gave was a very simple example and in the script I'm working on the check to see wether the object can be created is very complex and long, something I would rather not have to include everytime an object is created, furthermore I'd like to do this with a variety of different classes so segregating that check into a global function wouldn't really help me either. Also, you say you can clean up the extra bits by calling the destructor, but this does not clean up the memory, am I right? Previously, in PHP 4, one could unset() an object from within a function of that object, but it doesn't seem to work in PHP 5. I suppose I will implement your suggestion if I can't find any other solution but I'd rather have a cleaner way to do it, thank you for your help though.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.