[英]In a PHP class, how can I make it so that the variables are a specific type?
I have a PHP class, and I would like for it to have it so the variable is only a boolean? 我有一个PHP类,我想拥有它,因此该变量只是一个布尔值?
class TestClass {
private $isTrue;
public function __construct ( $isTrue) {
$this -> isTrue = $isTrue;
}
public function getIsTrue ($isTrue) {
return $this -> isTrue;
}
public function setIsTrue ($isTrue) {
$this -> isTrue = $isTrue;
}
}
Or is it something that I am required to do in the setter and constructor like this? 还是我需要像这样在setter和构造函数中执行此操作?
class TestClass {
private $isTrue;
public function __construct ( $isTrue) {
$this -> isTrue = (bool)$isTrue;
}
public function getIsTrue ($isTrue) {
return $this -> isTrue;
}
public function setIsTrue ($isTrue) {
$this -> isTrue = (bool)$isTrue;
}
}
Yes, in PHP < 7, you have to do this manually, as you have done. 是的,在PHP <7中,您必须手动完成此操作。
However, in PHP 7, you can use scalar typehinting to accomplish the same purpose: 但是,在PHP 7中,可以使用标量类型提示来实现相同的目的:
<?php
class TestClass {
private $isTrue;
public function __construct(bool $isTrue) {
$this->isTrue = $isTrue;
}
public function getIsTrue() {
return $this->isTrue;
}
public function setIsTrue(bool $isTrue) {
$this->isTrue = $isTrue;
}
}
$tc = new TestClass(true);
var_dump($tc->getIsTrue()); //true
$tc->setIsTrue(false);
var_dump($tc->getIsTrue()); //false
$tc->setIsTrue(1);
var_dump($tc->getIsTrue()); //true
You can also enable strict-types mode, and the last case will throw an error: 您还可以启用严格类型模式,最后一种情况将引发错误:
<?php
declare(strict_types=1);
// ...same code here ...
$tc->setIsTrue(1);
var_dump($tc->getIsTrue());
Will produce: 将产生:
Fatal error: Uncaught TypeError: Argument 1 passed to TestClass::setIsTrue() must be of the type boolean, integer given, called in /.../sth.php on line 27 and defined in /.../sth.php:16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.