Jump to content


Photo

Abort object instantiation


  • Please log in to reply
2 replies to this topic

#1 akheron

akheron
  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 19 April 2006 - 07:42 PM

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.
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";
}


#2 ToonMariner

ToonMariner
  • Members
  • PipPipPip
  • Advanced Member
  • 3,342 posts
  • LocationNewcastle upon Tyne, UK

Posted 19 April 2006 - 07:55 PM

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.
follow me on twitter @PHPsycho

#3 akheron

akheron
  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 19 April 2006 - 08:04 PM

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.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users