简体   繁体   English

PHP:OOP:返回错误

[英]PHP: OOP: Returning False

How can I check if my object has returned false or not? 如何检查我的对象是否返回false? I have the following class: 我有以下课程:

class Test {
    public function __construct($number) {
        if($number != '1') {
            return FALSE;
        }
    }
}

I've tried: 我试过了:

$x = new Test('1');
$x = new Test('2');

But when I var_dump($x), I get the same results. 但是当我var_dump($ x)时,我得到了相同的结果。 I want to do a: 我想做一个:

if(! $x = new Test('1')) {
    header("location: xxx...");
}

You cannot return anything from a constructor. 您不能从构造函数return任何内容。 If you want the construction of an object to fail, you'll have to throw an Exception . 如果要使对象的构造失败,则必须throw Exception

As deceze said, constructors cannot return a value. 正如deceze所说,构造函数无法返回值。 You could create a factory method that returns false, like: 您可以创建一个返回false的工厂方法,例如:

class Test
{
    public function __construct($number) {
        ...
    }

    public function factory($number) {
        return ($number != '1') ? false : new self($number);
    }
}

$x = Test::factory('1');
if (!$x) {
    header('Location: ...');
}

But I would use exceptions instead 但我会改用例外

class Test
{
    public function __construct($number) {
        if ($number != '1') {
            throw new IllegalArgumentException('Number must be "1"');
        }
        ...
    }
}

try {
    $x = new Test('1');
} catch (Exception $e) {
    header('Location: ...');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM