【问题标题】:PHP - constructor function doesn't return falsePHP - 构造函数不返回false
【发布时间】:2011-08-20 13:23:56
【问题描述】:

如何让下面的$foo 变量知道 foo 应该为假?

class foo extends fooBase{

  private
    $stuff;

  function __construct($something = false){
    if(is_int($something)) $this->stuff = &getStuff($something);
    else $this->stuff = $GLOBALS['something'];

    if(!$this->stuff) return false;
  }

}

$foo = new foo(435);  // 435 does not exist
if(!$foo) die(); // <-- doesn't work :(

【问题讨论】:

    标签: php class object constructor


    【解决方案1】:

    您不能从构造函数返回值。你可以使用exceptions

    function __construct($something = false){
        if(is_int($something)) $this->stuff = &getStuff($something);
        else $this->stuff = $GLOBALS['something'];
    
        if (!$this->stuff) {
            throw new Exception('Foo Not Found');
        }
    }
    

    在你的实例化代码中:

    try {
        $foo = new foo(435);
    } catch (Exception $e) {
        // handle exception
    }
    

    您还可以扩展异常。

    【讨论】:

    • 你的意思是php.net/manual/en/language.exceptions.php?但这不会显示 php 错误并停止脚本吗?我只想返回 false ...
    • 如果你 catch 就不行。从那时起,您可以做任何您想做的事情。
    • 那你做错了。相反,您应该分配给定的任何变量,然后调用 if ( $foo-&gt;is_falid() ){ /* do stuff */} ,请停止滥用 die() 函数。
    • 奇怪,即使您正在编写单个语句,您也需要在 try catch 中使用 {} 括号:s
    【解决方案2】:

    构造函数不应该返回任何东西。

    如果你需要在使用创建对象之前验证数据,你应该使用工厂类。

    编辑:是的,异常也可以解决问题,但是您不应该在构造函数中包含任何逻辑。这对单元测试来说很痛苦。

    【讨论】:

    • 什么是工厂类以及如何使用它? :D
    • @Alex,观看this video,这可能解释了其中的一些问题(是的,示例是在 java 中,但它是关于理论而不是“如何编写 hello world”)。跨度>
    【解决方案3】:

    你可以试试

    <?php
    
    function __construct($something = false){ 
        $this->stuff = $something; 
    }
    
    static function init($something = false){
        $stuff = is_int($something) ? &getStuff($something) : $GLOBALS['something'];
        return $stuff ? new self($stuff) : false;
    }
    
    
    $foo = foo::init(435);  // 435 does not exist
    if(!$foo) die();
    

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多