2

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
1

5 Answers 5

5

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.

1
  • 3
    It would be more appropriate to throw an \InvalidArgumentException (from SPL).
    – Florent
    Jul 12, 2012 at 13:00
2

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

1

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);
0
-3

Just return null if the parameter is not numeric:

<?php

    class Foo{

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

    }

?>
0
-3

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

2
  • This is how I set up all my function and methods so I have control over every response. For me, default variables and methods all return true/false for processing to determine errors and what not.
    – TurdPile
    Jul 12, 2012 at 15:46
  • So $class will be a boolean false rather than an instance of newClass if the constructor returns false. I wasn't aware of this. Where's it documented? It would be a useful link.
    – Mark Baker
    Jul 12, 2012 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.