【问题标题】:What is the difference between the use of casting in a class setter and type verification?在类设置器中使用强制转换和类型验证有什么区别?
【发布时间】:2018-07-06 14:07:16
【问题描述】:

我遇到了多种完成 setter 的方法,但我还没有在大型项目中使用它们...

我想知道这两个setter有什么区别,哪一个最好?

public function setId($id){
    if(is_int($id) && $id > 0){
        $this->_id = $id;
        return true;
    }

    return false;
}

或者

public function setId($id){
$id = (int) $id;
    if($id > 0){
        $this->_id = $id;
        return true;
    }

    trigger_error("The id of your object could not be set/assigned !);
}

trigger_error() 函数的用途是什么?当到处都有代码时,这些 setter 中的哪一个是有益的

注意:我正在使用 hydrate() 函数用数据库中的数据填充我的对象!

【问题讨论】:

  • 非常有用,非常感谢!

标签: php oop casting getter-setter setter


【解决方案1】:

如果您使用的是 PHP 7,您可以使用 IMHO 更好的版本

public function setId( int $id ){
    if($id > 0){
        $this->_id = $id;
        return true;
    }

    return false;
}

这意味着如果值不是 int,PHP 本身会抛出错误

仍然需要检查值是否大于0的条件,只要这个条件通过,那么函数将返回true,我假设小于0的值是无效值,这将返回false.

在您的第二个示例中,trigger_error() 用于记录或引发错误,表明该方法已传递无效值,因此需要在某个地方进行处理。

使用上面的代码版本,你还可以输入提示返回值...

public function setId( int $id ): boolean {
    if($id > 0){
        $this->_id = $id;
        return true;
    }

    return false;
}

如果您需要坚持原来的选项,那么在我看来,第一个选项更好,第二个选项强制转换为 int,然后检查结果是否为 int,所以这没有用。

【讨论】:

  • 请注意,在 setter 中使用 typehints 会使调用者承担强制转换的责任。如果您的输入数据可能是字符串类型的(当来自$_GET 或$_POST 变量或来自数据库查询时),这将导致在每次调用setter 时重复(int) 或intval() 转换。像在示例 #2 中所做的那样将类型转换放在 setter 中会在将来为您节省一些击键。
猜你喜欢
  • 2012-02-10
  • 2021-05-28
  • 2013-12-27
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多