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
topherg
  • 4,203
  • 4
  • 37
  • 72
  • possible duplicate of [PHP constructor to return a NULL](http://stackoverflow.com/questions/2214724/php-constructor-to-return-a-null) – Esailija Jul 12 '12 at 13:04

5 Answers5

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.

FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
2

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

Esailija
  • 138,174
  • 23
  • 272
  • 326
Ugo Méda
  • 1,205
  • 8
  • 23
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);
Lawrence DeSouza
  • 984
  • 5
  • 16
  • 34
-3

Just return null if the parameter is not numeric:

<?php

    class Foo{

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

    }

?>
James Woodruff
  • 963
  • 6
  • 10
-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

TurdPile
  • 976
  • 1
  • 7
  • 21
  • 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 '12 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 '12 at 15:50