topherg
topherg

Reputation: 4303

Stopping a class from being instanced if incorrect parameters

Is it possible to create a PHP class that would act like this:

class Foo
{
    function __construct($param)
    {
        if (!is_numeric($param))
        {
            // stop class
        }
    }
}

$a = new Foo(2);
$b = new Foo('test');

var_dump($a);
var_dump($b);

which will return

object(Foo)[1]
null

Upvotes: 2

Views: 115

Answers (5)

TurdPile
TurdPile

Reputation: 1036

pretty much as you have it:

<?
public class newClass {

    public __CONSTRUCT($param = false){

        if(!is_numeric($param)){
            return false
        }

    }

}

$class = new newClass(1);
if($class){
    //success / is a number
}else{
    // fail, not a number, so remove the instance of the class
    unset($class);
}
?>

Setting $param = false inside the arguments for the constructor will tell the script to set it to false if there is no input

Upvotes: -3

Lawrence DeSouza
Lawrence DeSouza

Reputation: 1026

You could try to throw an exception and catch it from another function in the same scope as the variable declaration:

class Foo
{
    function __construct($param)
    {

        if( !is_numeric($param) )
            return true;
        else
            throw new Exception();

    }


}

function createFooObject($v){
    try{ $x = new Foo($v); return $x; }
    catch(Exception $e){
        unset($x);
    }
}

$a = createFooObject(2);
$b = createFooObject('test');



var_dump($a);
var_dump($b);

Upvotes: 1

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28929

The only way I'm aware of to stop creating of a new object while not immediately terminating the script is to throw an exception:

class Foo {
    public function __construct($param) {
        if (!is_numeric($param)) {
            throw new \InvalidArgumentException('Param is not numeric');
        }
    ...
}

Of course, you'd have to be sure and catch the exception in the calling code and handle the problem appropriately.

Upvotes: 5

Ugo M&#233;da
Ugo M&#233;da

Reputation: 1215

Create a static create($param) that returns a new instance or null if $param is invalid. You could also consider using Exceptions.

Upvotes: 2

James Woodruff
James Woodruff

Reputation: 973

Just return null if the parameter is not numeric:

<?php

    class Foo{

       public function __construct($param = null){
          if( !is_numeric($param) ){
             return null;
          }
       }

    }

?>

Upvotes: -3

Related Questions