Conditional Object Creation.

A

Anonymous

Guest
Hi,
Would like to know if some thing like this is possible

Code:
<?php
    class MyClass
    {
        function __construct($needed_parameter)
        {
            if ($this->isValid($needed_parameter)) {
                //object should not be created.
            }
            else {
                //object creation is successfull
            }
        }
        
        private function isValid($parameter)
        {
            if ($parameter == 'some valid condition') {
                return true;
            }
            else {
                return false;
            }
        }
        
        public function callMe()
        {
            return 'object has been created';
        }
    }

//case 1 :
    $obj_valid = new MyClass('some valid condition');
    $obj_valid->callMe();

//case 2 :
    $obj_invalid = new MyClass('some Invalid condition');
    $obj_invalid->callMe();

?>

What I need is if the user tries to create the object with a Invalid parameter, the object should not be
created. So when user tries to call a member function PHP throws a error.

Any help would be much appriciated.

Thanks
Varma
 
imo - with basic knowledge about the PHP classes - it isn't. If it is I expect someone will correct me :p

I suggest that if the parameters are not valid, you throw an exception yourself...

Coditor
 
Coditor said:
imo - with basic knowledge about the PHP classes - it isn't. If it is I expect someone will correct me :p

I suggest that if the parameters are not valid, you throw an exception yourself...

Coditor

Yea, 've used exception to do the job. No idea if there is any other way :)

Thanks for the suggestion

Varma
 
Back
Top